Detecting which UIButton was pressed in a UITableView

前端 未结 26 2904
小蘑菇
小蘑菇 2020-11-22 00:40

I have a UITableView with 5 UITableViewCells. Each cell contains a UIButton which is set up as follows:

- (UITableView         


        
26条回答
  •  说谎
    说谎 (楼主)
    2020-11-22 00:52

    // how do I know which button sent this message?
    // processing button press for this row requires an indexPath.
    

    Pretty straightforward actually:

    - (void)buttonPressedAction:(id)sender
    {
        UIButton *button = (UIButton *)sender;
        CGPoint rowButtonCenterInTableView = [[rowButton superview] convertPoint:rowButton.center toView:self.tableView];
        NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:rowButtonCenterInTableView];
        MyTableViewItem *rowItem = [self.itemsArray objectAtIndex:indexPath.row];
        // Now you're good to go.. do what the intention of the button is, but with
        // the context of the "row item" that the button belongs to
        [self performFooWithItem:rowItem];
    }
    

    Working well for me :P

    if you want to adjust your target-action setup, you can include the event parameter in the method, and then use the touches of that event to resolve the coordinates of the touch. The coordinates still need to be resolved in the touch view bounds, but that may seem easier for some people.

提交回复
热议问题