【发布时间】:2019-11-12 23:53:30
【问题描述】:
我正在尝试管理同一个自定义表格视图单元格中的两个按钮。 添加了两个名为 Yes 和 No 的按钮。如果选择 Yes 按钮,No 按钮将处于非活动状态,而 Yes 按钮将变为活动状态。
这是我需要的图片
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "tableCell") as! TableViewCell
cell.yesButton.tag = 101
cell.noButton.tag = 102
cell.yesButton.addTarget(self, action: #selector(buttonClicked(sender:)), for: UIControl.Event.touchUpInside)
cell.noButton.addTarget(self, action: #selector(buttonClicked(sender:)), for: UIControl.Event.touchUpInside)
return cell
}
@objc func buttonClicked(sender: AnyObject) {
let buttonPosition = (sender as AnyObject).convert(CGPoint.zero, to: tableList)
let indexPath = tableList.indexPathForRow(at: buttonPosition)
if sender.tag == 101 {
if indexPath != nil {
print("Cell indexpath = \(String(describing: indexPath?.row))")
}
}
if sender.tag == 102 {
if indexPath != nil {
print("Cell indexpath = \(String(describing: indexPath?.row))")
}
}
}
【问题讨论】:
-
那么问题是什么?
-
严格来说,您不使用 custom 表格视图单元格。您正在使用带有自定义对象的标准表格视图单元格。不要那样做。使用 real
custom样式和包含IBOutlets的自定义类设计一个表格视图单元格。在此单元格中,您可以实现自定义逻辑来控制按钮。处理标签来识别 UI 元素已经过时了很长时间。 -
您可以在标签中使用枚举,例如 enum SenderTags: Int { case foo = 101, case foo2 = 102 }
标签: ios swift uitableview uibutton