Search code examples
iosobjective-cuitableviewcustom-cell

IOS/Objective-C: Detect Button Press in Custom Tableview Cell?


For a feed View controller, I have a tableview with some custom cells that have buttons for like, comment and share I would like to perform different actions depending on which button is pushed.

My initial thought was to simply wire the buttons in the custom cell in storyboard to action methods in the custom cell. However, I have gotten confused on how methods in the custom cell .m file interact with the TableView in the View Controller.

- (IBAction)likeButtonPressed:(id)sender {
 CGPoint buttonPosition = [sender convertPoint:CGPointZero toView:self.tableView];
NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:buttonPosition];
//do something
}

Can anyone clarify whether a button push in a cell can be wired in storyboard and how this plays with the delegate methods on the viewcontroller, cellforrowatindexpath and didselectrowatindexpath?

Or if this is not the right way to do it, would appreciate any suggestions on better way. Thanks in advance for any suggestions.


Solution

  • Instead of using the delegate or tags, you can simply use blocks to do that. Blocks are much more easy and simple to use than the delegate pattern and recommended.

    In Swift too, you shall see the extensive use of closures (blocks in Objective-C) than any other pattern.

    Example:

    1. UITableViewDataSource Methods

    - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
    {
        return 1;
    }
    
    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
    {
        TableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
        cell.likeButtonTapHandler = ^{
            NSLog(@"Like Button Tapped");
            //ADD YOUR CODE HERE
        };
        cell.commentButtonTapHandler = ^{
            NSLog(@"Comment Button Tapped");
            //ADD YOUR CODE HERE
        };
        cell.shareButtonTapHandler = ^{
            NSLog(@"Share Button Tapped");
            //ADD YOUR CODE HERE
        };
        return cell;
    }
    

    2. Custom UITableView Cell

    @interface TableViewCell : UITableViewCell
    
    @property (nonatomic, copy) void(^likeButtonTapHandler)(void);
    @property (nonatomic, copy) void(^commentButtonTapHandler)(void);
    @property (nonatomic, copy) void(^shareButtonTapHandler)(void);
    
    @end
    
    @implementation TableViewCell
    
    - (IBAction)likeButtonTapped:(UIButton *)sender
    {
        self.likeButtonTapHandler();
    
    }
    
    - (IBAction)commentButtonTapped:(UIButton *)sender
    {
        self.commentButtonTapHandler();
    }
    
    - (IBAction)shareButtonTapped:(UIButton *)sender
    {
        self.shareButtonTapHandler();
    }