JMD
JMD

Reputation: 1590

Selector of an object inside custom cell

I have a switch inside a custom cell. The switch is allocated and set to the accessoryView of the cell inside the .m file of the custom cell.

However, I need the selector method for the switch to be handled in the ViewController of the tableView the custom cell resides in.

Currently when clicking the switch I get a crash that it can't find the selector, most likely because its looking in the cell's .m.

How can I declare my switch to have its selector look in the correct location?

edit as per request...

//cell .m
- (void)setType:(enum CellType)type
{
    if (_type == SwitchType)
    {
         UISwitch *switchView = [[UISwitch alloc] init];
         [switchView addTarget:self action:@selector(flip:) forControlEvents:UIControlEventValueChanged];
         self.accessoryView = switchView;
    }
}

Upvotes: 0

Views: 56

Answers (2)

Ryan Poolos
Ryan Poolos

Reputation: 18561

You could create your switch as a public property then set its target in cellForRowAtIndex:

@interface CustomCell : UITableViewCell

@property (nonatomic, strong) UISwitch *switch;

Or you could create a custom NSNotification that is fired off. And have your viewController listen for the notification then deal with it.

Blocktastic :)

You could also get fancy with blocks.

typedef void(^CustomCellSwitchBlock)(BOOL on);

@interface CustomCell : UITableViewCell

@property (nonatomic, readwrite) CustomCellSwitchBlock switchAction;

Then in your CustomCell.m:

- (void)handleSwitch:(UISwitch *)switch
{
    switchAction(switch.on);
}

Then in your cellForRowAtIndex::

cell.action = ^(BOOL on){
    if (on) {
        // Perform On Action
    } else {
        // Perform Off Action
    }
};

Upvotes: 0

Shizam
Shizam

Reputation: 9672

Sounds like the job for a delegate. Create a protocol in your cell interface like:

@protocol MyCellDelegate <NSObject>
- (void)myCell:(MyCell *)sender switchToggled:(BOOL)value;
@end

and specify a delegate

id <MyCellDelegate> delegate;

Then in your MyCell.m, when the switch is toggled check if the delegate is defined, if so call it:

if (self.delegate != nil && [self.delegate respondsToSelector:@selector(myCell:switchToggled:)]) {
    [self.delegate myCell:self switchToggled:switch.value]
}

And in your ViewController be sure to set the ViewController to be the delegate for the cell and implement the protocol method.

Upvotes: 3

Related Questions