在表格视图单元格中单击按钮时执行功能

时间:2016-03-08 06:47:32

标签: ios swift tableviewcell

我的tableview单元格中有一个按钮。如何转换以下代码行,以便在单击按钮(而不是行)时执行相同的功能?提前谢谢。

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath:    NSIndexPath){

    // Get Cell Label
    let indexPath = tableView.indexPathForSelectedRow!
    let currentCell = tableView.cellForRowAtIndexPath(indexPath) as! PostCell

    if currentCell.updateBtn.hidden == false {
        valuetoPass = currentCell.favorTitle.text
        valuetoPass_desc = currentCell.descriptionText.text
        postKey = currentCell.post.postKey
        performSegueWithIdentifier("seguetoVC", sender: self)
    }

    if currentCell.bidBtn.hidden == false {
          bidInt = currentCell.post.bids
          postKey = currentCell.post.postKey
          passUsername = currentCell.post.username
          performSegueWithIdentifier("seguetoBidVC", sender: self)
    }

}

4 个答案:

答案 0 :(得分:0)

您可以为单元格按钮添加@selector,并为每行指定行值作为标记。当您点击任何单元格按钮时,您可以调用在@selector中添加的方法,并通过按钮标记,您可以获取该单元格的索引。

例如:在用于行功能的单元格中:

    [cell.btn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
cell.btn.tag = indexPth.row;

功能:

-(void) btnClick:(UIButton *) btn {
    NSIndexPath *path = [NSIndexPath indexPathForRow:btn.row inSection:0];

}

由于

答案 1 :(得分:0)

您可以使用block执行此操作。在创建单元格时,在cellForRowAtIndexPath中设置块。只要在按钮的IBAction方法中点击按钮,就调用此块。

答案 2 :(得分:0)

使用闭包来录制单元格中的事件,比委托更容易。

tutorial

答案 3 :(得分:0)

    Proper way is, create cell class and add action to cell class from xib. if button pressed then cell class method will be called and it will call delegate method that will be implemented by controller. e.g


protocol TableViewCellDelegate: NSObject {
        func TableViewCell(cell: UITableViewCell, ButtonPressed sender: AnyObject)
    }
    class TableViewCell: UITableViewCell {
        weak var delegate: CommentTableViewCellDelegate
    }
    IBACtion func sender() {
        self.delegate.TableViewCell(self, ButtonPressed: sender)
    }

    In Controller, implement delegate of cell

    func TableViewCell(cell: UITableViewCell, editButtonPressed sender: AnyObject) {
        var indexPath: NSIndexPath = self.tableViewComments(forCell: cell)
    }