在单元格 CustomTableViewCell 内按下按钮时删除单元格 [英] Remove cell when button pressed inside cell CustomTableViewCell

查看:25
本文介绍了在单元格 CustomTableViewCell 内按下按钮时删除单元格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在选中复选框时删除单元格,但该功能会一直删除索引 0 处的单元格而不是选定单元格索引

Hi I'm trying to remove the cell when the checkbox is selected but the function keeps removing cell at index 0 instead of selected cell index

设置带有标签的单元格

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)
}

点击单选按钮时调用的函数

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

RadioTapped 总是打印Radio tapped at 0"

RadioTapped always print "Radio tapped at 0"

推荐答案

您当前的问题是线路:

delegate?.RadioTapped(sender.tag)

应该是:

delegate?.RadioTapped(tag)

因为它是设置单元格的标签.

Since it is the cell's tag being set.

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

But do not use tags for this. Update the cell's delegate method to pass itself as the parameter. Then the delegate can determine the cell's indexPath from the table view.

更新的协议:

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

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

Updated cell tap handler:

@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

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

Update delegate method in the table view:

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

这篇关于在单元格 CustomTableViewCell 内按下按钮时删除单元格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆