簡體   English   中英

在tableview單元格內獲取一個按鈕,使其與didSelectCell相同

[英]Get a button inside tableview cell to run the same as didSelectCell

我在單元格內有一個帶有UIButton的tableview。

我在didSelectRowAtIndexPath中創建了一些功能。 我想讓用戶也單擊按鈕時運行相同的功能/方法。

如何使buttonPressed方法運行didSelectRowAtIndexPath?

如果無法執行此操作,則可以將功能移至新方法,然后都調用此新方法。 但是,如何從按鈕按下的方法獲取單元格indexPath?

  1. 找到包含按鈕的UITableViewCell對象(必須是其容器視圖之一,僅在超級視圖鏈上)。
  2. 使用[UITableView indexPathForCell:]查找indexPath。
-(IBAction)playButtonPressed:(id)sender {
    NSLog(@"button pressed");
    UIButton *button = (UIButton *)sender;
    UITableViewCell *cell = (UITableViewCell *)button.superview.superview;
    UITableView *curTableView = (UITableView *)cell.superview;
    NSIndexPath *indexPath = [curTableView indexPathForCell:cell];

    [self didSelectRowOrButtonAtIndexPath:indexPath];
}

我創建了一個新方法didSelectRowOrButtonAtIndexPath,並從buttonPressed和didSelectRowAtIndexPath中都調用了此方法,並傳入了要在我的方法中使用的索引路徑。

cellForRowAtIndexPath ,將indexPath.row分配給按鈕的tag (假設您只需要該行-想法是將indexPath附加到按鈕上, tag只是這樣做的一種方法)。

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

    // Init / Reuse the cell ...

    cell.button.tag = indexPath.row;

    return cell;
}

-(void)buttonPressed:(UIButton*)button {
    [self method:button.tag];
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM