在单元格CustomTableViewCell中按下按钮时删除单元格

时间:2017-07-21 16:26:36

标签: swift uitableview

您好我在选中复选框时尝试删除单元格,但该函数一直在删除索引0处的单元格而不是选定的单元格索引

使用标记设置单元格

let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! TableViewCell
    let task = tasks[indexPath.row]
    cell.delegate = self
    cell.tag = indexPath.row


    print("The tag is \(cell.tag)")

CustomTableViewCell

protocol TableViewCellDelegate {
func RadioTapped(_ tag: Int)


}

class TableViewCell: UITableViewCell  {

var delegate: TableViewCellDelegate?

@IBOutlet var radioButton: BEMCheckBox!
@IBOutlet var taskText: UILabel!
@IBAction func radioTapped(_ sender: UIView){
    delegate?.RadioTapped(sender.tag)
}

点击radiobutton时调用的函数

func RadioTapped(_ tag: Int) {
    print("Radio Tapped at \(tag)")
}

RadioTapped始终打印"无线电点击0"

2 个答案:

答案 0 :(得分:2)

您的直接问题是:

delegate?.RadioTapped(sender.tag)

应该是:

delegate?.RadioTapped(tag)

因为正在设置单元格标记。

但是不要为此使用标签。更新单元格的委托方法以将其自身作为参数传递。然后委托可以从表视图中确定单元格的indexPath。

更新协议:

protocol TableViewCellDelegate {
    func radioTapped(_ cell: TableViewCell)
}

更新了单元格点击处理程序:

@IBAction func radioTapped(_ sender: UIView){
    delegate?.radioTapped(self)
}

更新了cellForRowAt:

let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! TableViewCell
let task = tasks[indexPath.row]
cell.delegate = self

在表格视图中更新委托方法:

func radioTapped(_ cell: TableViewCell) {
    if let indexPath = tableView.indexPath(for: cell) {
        print("Radio Tapped at \(indexPath)")
    }
}

答案 1 :(得分:1)

您正在为单元格设置标记但访问按钮的标记,因此请设置单元格的按钮标记。

cell.radioButton.tag = indexPath.row