UIControl - change assigned selectors: addTarget & removeTarget

I use 10 buttons in my interface and from time to time you need to change the button selector.

I need to use:

-(void)removeTarget:(id)target action:(SEL)action forControlEvents:(UIControlEvents)controlEvents 

before i change the selector or can i just use:

 -(void)addTarget:(id)target action:(SEL)action forControlEvents:(UIControlEvents)controlEvents 

I am concerned that if I change the selector using the addTarget: method, the sysType: method is the method by which I essentially β€œdrain” the selectors to start UIButton when it is pressed.

+3
source share
2 answers

Yes, you should always delete a previously added target before assigning a new target to a button. Like this ---

 UIButton *btn = [UIButton buttonWithType:UIButtonTypeRoundedRect]; [btn setFrame:CGRectMake(50, 50, 200, 50)]; [btn setTag:101]; [btn addTarget:self action:@selector(method1) forControlEvents:UIControlEventTouchUpInside]; [self.view addSubview:btn]; btn = (UIButton *)[self.view viewWithTag:101]; [btn removeTarget:self action:@selector(method1) forControlEvents:UIControlEventTouchUpInside]; [btn addTarget:self action:@selector(method2) forControlEvents:UIControlEventTouchUpInside]; 

now if you do it

 btn = (UIButton *)[self.view viewWithTag:101]; [btn addTarget:self action:@selector(method2) forControlEvents:UIControlEventTouchUpInside]; 

then both the methods method1 and the method will be called.

Hope this helps.

+12
source

Yes, you will need to delete the old goal / action, or old and new actions will be performed.

+2
source

Source: https://habr.com/ru/post/913965/


All Articles