Remove cell when button pressed inside cell CustomTableViewCell

巧了我就是萌 提交于 2020-03-22 09:49:14

问题


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

Set up Cell with tag

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

Function called when radiobutton is tapped

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

RadioTapped always print "Radio tapped at 0"


回答1:


Your immediate issue is the line:

delegate?.RadioTapped(sender.tag)

It should be:

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.

Updated protocol:

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

Updated cell tap handler:

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

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



回答2:


You are setting tag for cell but accessing tag of button so set cell's button tag.

cell.radioButton.tag = indexPath.row


来源:https://stackoverflow.com/questions/45242514/remove-cell-when-button-pressed-inside-cell-customtableviewcell

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!