IOS prototype cells with UIControls inside

So far, I only needed to implement prototype cells with predefined projects (normal, subtitle, etc.), and this was not a problem.

Now I need to implement prototype cells that contain some controls, such as a segmented switch, switch, or whatever. The problem is that I was not able to figure out how actions work and how they relate to the control. Also, I did not find a single example of how various prototype cells are implemented inside one UITableViewController.

I know this is kind of a general question, but I would appreciate some pointers here. Maybe someone knows about some kind of documentation, tutorial, etc. Well, any help will do,

Thnaks in advance.

+6
source share
1 answer

It took me a while to figure out how to use prototype cells. If you want to access the user interface elements inside the prototype cell, you need to subclass UITableViewCell and assign it to the prototype cell in Interface Builder. Then you need to define the IBOutlet properties manually, for example:

@interface OptionSwitchCell : UITableViewCell @property (weak, nonatomic) IBOutlet UISwitch* switchControl; @end 

After that, you can connect the interface elements by dragging the control from the element to the property definition in the assistant window. Instead, IBActions can be defined inside the owner of the View Controller. You can control drag and drop from an interface element to the View Controller header file and create an action. Inside the implementation of an action, you probably want to know which cell triggered the action. I do it like this:

 @implementation SomeTableViewController - (IBAction)toggleActivity:(id)sender { OptionSwitchCell* cell = (OptionSwitchCell *)[sender superview].superview; NSIndexPath *indexPath = [self.tableView indexPathForCell:cell]; ... } @end 

Another solution for finding the appropriate cell path and index (by jrturton):

 - (IBAction)toggleActivity:(id)sender { CGPoint hitPoint = [sender convertPoint:CGPointZero toView:self.tableView]; NSIndexPath *hitIndex = [self.tableView indexPathForRowAtPoint:hitPoint]; OptionSwitchCell* cell = (OptionSwitchCell *)[self.tableView cellForRowAtIndexPath:hitIndex]; ... } 

Although this is a bit bizarre, I have not yet found a better solution. Hope this helps.

+11
source

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


All Articles