Get UIButton Presentation Included

I have a UIButton on a custom UITableViewCell, I have a "done" method.

How can I get a CustomTableViewCell via a button?

-(IBAction)done:(id)sender { (CustmCell((UIButton)sender).viewTheButtonIsOn...).action } 
+6
source share
4 answers

The answer from CodaFi is most likely sufficient, but it makes the assumption that the button is added directly to the table cell. A bit more complex but safe bit of code might look something like this:

 -(IBAction)done:(id)sender { UIView *parent = [sender superview]; while (parent && ![parent isKindOfClass:[CustomCell class]]) { parent = parent.superview; } CustomCell *cell = (CustomCell *)parent; [cell someAction]; } 
+12
source

If it is added directly to the cell as a preview, you can use -superview to get its parent view. In addition, you need to specify pointers, because objects are never taken by value, and is only specified in Objective-C.

 -(IBAction)done:(id)sender { [(CustmCell*)[(UIButton*)sender superview]someAction]; } 
+4
source

Another way is to subclass the UIButton with the CustomCell property to directly access the CustomCell object. This is technically better code than viewing supervisors.

+2
source

You also need to think about the contentView and any other sub-cell in which the button may be contained now or in the future. Be safe and cross the parent hierarchy.

 var parent = button.superview while let v = parent where !v.isKindOfClass(MyCustomCell) { parent = v.superview } // parent is now your MyCustomeCell object 
+1
source

All Articles