Do I have to delete Target before adding addTarget

UIControl - change assigned selectors: addTarget and removeTarget

Indicates that you must delete the target before changing to another. However, what if I set a target in cellForRowAtIndexPath? Do I have to delete the target before adding it again, even if it does not change? Will he call the method twice if I don’t delete it, or will he just overwrite it?

[cell.cellSwitch removeTarget:self action:@selector(notifySwitchChanged:) forControlEvents:UIControlEventValueChanged]; [cell.cellSwitch addTarget:self action:@selector(notifySwitchChanged:) forControlEvents:UIControlEventValueChanged]; 
+6
source share
2 answers

Following my experience, it will be called only once.

But IMO, it is better to use removeTarget always, because the code may be changed in the future. And someday you may need to add some goals and selectors.

Be safe, scalable, and maintainable.

 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { UITableViewCell *cell = // code with reuse identifier ... if(cell == nil) { // making view for cell .... } // myAction will be called ONLY ONCE after many times of scrolling [cell.myButton addTarget:self action:@selector(myAction:) forControlEvents:UIControlEventTouchUpInside]; return cell; } 
0
source

Instead of adding / removing targets, I found that if I already subclass UITableViewCell , I will add a new delegate and put the delegate in the view controller. That way, any methods called by the delegate can go through the whole cell, and so I can get the index path of the cell by calling the UITableView indexPathForCell method.

0
source

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


All Articles