【问题标题】:UITableCell button touchUpInside with index of cell whos button was clickedUITableCell 按钮 touchUpInside 与单元格的索引谁的按钮被点击
【发布时间】:2014-01-17 20:44:45
【问题描述】:

我有一个带有 UITableCells 的 UITable,如下所示:

[我的标签我的按钮]

[我的标签我的按钮]

[我的标签我的按钮]

[我的标签我的按钮]

我希望我的 handlerCellButtonClicked 也能获得对单元格索引的引用。当按钮被触摸时,我怎样才能获得对这个索引的引用?

/** called by table to get the cell needed by the index */
-(UITableViewCell*)tableView:(UITableView *) tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    ...
    //init cell
    ...
    //configure the cells custom button handlers
    [cell.myButton addTarget:self action:@selector(handlerCellButtonClicked) forControlEvents:UIControlEventTouchUpInside];

    return cell;
}

/** handler when the button in the cell is clicked */
- (void)handlerCellButtonClicked{
    NSLog(@"cell myButton clicked");
}

【问题讨论】:

标签: iphone objective-c


【解决方案1】:

利用UIButton Tag 属性。

-(UITableViewCell*)tableView:(UITableView *) tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

    //init cell
    //configure the cells custom button handlers

    cell.myButton.tag = indexPath.row;
    [cell.myButton addTarget:self action:@selector(handlerCellButtonClicked:) forControlEvents:UIControlEventTouchUpInside];

    return cell;
}

/** handler when the button in the cell is clicked */
- (void)handlerCellButtonClicked:(UIButton *)sender
  {
     NSLog(@"%d cell myButton is clicked", sender.tag);
  }

【讨论】:

  • 你如何确定选择器会通过发件人?
  • (handlerCellButtonClicked:) 应该将发送者传递给目标,对吧?
  • 您只能使用 addTarget @selector 方法将 (UIButton*) 对象作为参数传递。就是这样。此外,“UIControlEventTouchUpInside”事件会将按钮作为参数发送。希望您理解。
  • @Ramshad:这很好用,在方法发送 UIButton 之后添加冒号 @selector(handlerCellButtonClicked:) ,我可以获得标签。我遇到的问题是,如果我删除行,则标签不正确,因为索引已更改。但我可以将此作为另一个问题发布。感谢您的帮助。
  • @Ramshad 标签必须是 NSInteger 还是可以是任何对象?
猜你喜欢
  • 2021-02-24
  • 2013-01-20
  • 2019-04-02
  • 1970-01-01
  • 2012-05-12
  • 1970-01-01
  • 2014-01-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多