UIControl 无法识别表格视图单元格内的点击,从 iOS 14 停止工作

Joh*_*oah 1 ios swift

在 iOS 14 出现之前,我有一个应用程序。我停止使用 Swift 几个月了,现在,模拟器正在运行 iOS 14,从那时起,我遇到了一个问题,我在 tableView 单元格中的 UIControl 没有注册点击。

这是我的 TableView(简单,没有自定义或任何东西):

private let tableView: UITableView = {
    let table = UITableView(frame: .zero, style: .plain)
    table.translatesAutoresizingMaskIntoConstraints = false
    table.backgroundColor = .white
    table.separatorInset.right = table.separatorInset.left
    
    
    return table
}()
Run Code Online (Sandbox Code Playgroud)

这是我尝试设置点击手势的方式:

extension TodoListVC: UITableViewDelegate, UITableViewDataSource {

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: todoCellIdentifier, for: indexPath) as! TodoCell
    
    let todo = todoListViewModel.todos[indexPath.row]
    cell.model = todo
    cell.selectionStyle = .none
    
    
    let checkBox = cell.checkbox
    checkBox.index = indexPath.row
    checkBox.addTarget(self, action: #selector(onCheckBoxValueChange(_:)), for: .valueChanged) // touchUpInside also does not work.
    
    
    return cell
}

@objc func onCheckBoxValueChange(_ sender: UICheckBox) {
    var todo = todoListViewModel.todos[sender.index]
    todo.isDone = sender.isChecked
    tableView?.reloadRows(at: [IndexPath(row: sender.index, section: 0)], with: .none)
    todoListView.reloadProgress()
}
}
Run Code Online (Sandbox Code Playgroud)

该复选框是我从教程中复制的自定义 UIControl,它在 iOS 14 之前运行良好,我现在不知道它有什么问题。该文件非常大,无法在此处添加,但如果有必要,我可以提供代码。

Rob*_*Rob 8

转到您的TodoCell并将其添加到您的initializer

 override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
    
    super.init(style: style, reuseIdentifier: reuseIdentifier)
    contentView.isUserInteractionEnabled = true

}
Run Code Online (Sandbox Code Playgroud)

它会重新开始工作。如果您尚未以编程方式创建单元格,则可以执行以下操作:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: todoCellIdentifier, for: indexPath) as! TodoCell

let todo = todoListViewModel.todos[indexPath.row]
cell.model = todo
cell.selectionStyle = .none
cell.contentView.isUserInteractionEnabled = true

let checkBox = cell.checkbox
checkBox.index = indexPath.row
checkBox.addTarget(self, action: #selector(onCheckBoxValueChange(_:)), for: .valueChanged) // touchUpInside also does not work.


return cell
}
Run Code Online (Sandbox Code Playgroud)

要调试,您可以打印 的值,contentView.isUserInteractionEnabled它会为您提供布尔值,并使用它您可以查看它是否是问题。它很可能会返回false,并且上述解决方案适用于 iOS 14 和 Xcode 12。