问题检测按钮cellForRowAt

A.A*_*mal 3 uitableview ios swift

我需要检测是否已在UITableViewController中单击该按钮

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

 let LikesBtn = cell.viewWithTag(7) as! UIButton

}
Run Code Online (Sandbox Code Playgroud)

vad*_*ian 9

Swift中最简单,最有效的方法是回调闭包.

  • 子类UITableViewCell,viewWithTag识别UI元素的方式已经过时.
  • 将自定义单元格的类设置为子类的名称,并ButtonCellIdentifier在Interface Builder 中将标识符设置为.

  • 添加一个callback属性.

  • 添加操作并将按钮连接到操作.

    class ButtonCell: UITableViewCell {
    
        var callback : (()->())?
    
        @IBAction func buttonPressed(_ sender : UIButton) {
           callback?()
        }
    }
    
    Run Code Online (Sandbox Code Playgroud)
  • cellForRow回调分配到自定义单元格.

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "ButtonCellIdentifier", for: indexPath) as! ButtonCell
         cell.callback = {
             print("Button pressed", indexPath)  
         }
         return cell
      }
    
    Run Code Online (Sandbox Code Playgroud)
  • 按下按钮时,将调用回调.捕获索引路径.