Search code examples
iosios6uitableview

Setting IBAction on Custom Cell from xib?


I created a custom cell in a xib (using Storyboards in iOS6 but created separate xib for cell) and now I'm trying to connect my speaker button to an IBAction in my UITableViewController sublcass.

enter image description here

I registered my cell in my viewDidLoad:

[self.tableView registerNib:[UINib nibWithNibName:@"MissedWordTableCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"MissedWordCell"];

I've tried a couple of different ways to add the target. For example, in my tableView:cellForRowAtIndexPath, I tried to add the target directly.

static NSString *CellIdentifier = @"MissedWordCell";
MissedQuestionEntity *missedQuestion;

// forIndexPath: is iOS6
MissedWordTableCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
// Add target here?  Didn't work. @selector(playWordAction) or @selector(playWordAction:) 
//    [cell.playAudioBtn addTarget:self action:@selector(playWordAction) forControlEvents:UIControlEventTouchUpInside];

I also tried to set the File Owner to my Table View Controller in my Custom cell xib, but still didn't work.

Here's my error message:

2013-07-30 07:47:15.833 Spanish[69420:c07] *** Terminating app due to uncaught exception     
'NSInvalidArgumentException', reason: '-[__NSArrayI doIt]: unrecognized selector sent to instance     
0xec34430'
*** First throw call stack:
(0x231e012 0x172de7e 0x23a94bd 0x230dbbc 0x230d94e 0x1741705 0x6752c0 0x675258 0x736021 0x73657f 0x7356e8     
0x6a4cef 0x6a4f02 0x682d4a 0x674698 0x1c0bdf9 0x1c0bad0 0x2293bf5 0x2293962 0x22c4bb6 0x22c3f44 0x22c3e1b     
0x1c0a7e3 0x1c0a6

Solution

  • In UITableViewCell just register the property:

    @property (strong, nonatomic) IBOutlet UIButton *playSoundButton;
    

    In your UITableViewController:

    - (void)viewDidLoad
    {
        [super viewDidLoad];
        [self.tableView registerNib:[UINib nibWithNibName:@"YourCustomCell" bundle:nil] forCellReuseIdentifier:@"YourCustomCell"];
        // ...
    }
    
    
    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
    {
       YourCustomCell *cell = [tableView dequeueReusableCellWithIdentifier:@"YourCustomCell"];
    
       [[cell playSoundButton] addTarget:self action:@selector(playWordAction:) forControlEvents:UIControlEventTouchUpInside];
    
        //...
    }
    
    -(IBAction) playWordAction:(id) sender
    {
        // do what you want to
    }