Reputation: 157
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"
Upvotes: 2
Views: 2404
Reputation: 318774
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)")
}
}
Upvotes: 7
Reputation: 55
You are setting tag for cell but accessing tag of button so set cell's button tag.
cell.radioButton.tag = indexPath.row
Upvotes: 1