繁体   English   中英

从UITableViewCell到ViewController的按钮操作

[英]Button Action from UITableViewCell to ViewController

我正在尝试实现Delegate方式,以便在从UITableViewCell到ViewController的按钮上执行某些操作。 以下是我到目前为止的情况 -

TableViewCell:

protocol UserCellDelegate : class {
    func disableUser(cell: UserCell, button: UIButton)
}

class UserCell : UITableViewCell {

    @IBOutlet weak var userLabel: UILabel!
    @IBOutlet weak var userDescription: UILabel!

    @IBOutlet weak var writeOutUser: UIButton!

    weak var delegate: UserCellDelegate?

    override func awakeFromNib() {
        super.awakeFromNib()
        writeOutUser.layer.cornerRadius = 5.0
    }


    @IBAction func disableUserButtonAction(sender: UIButton) {
        delegate?.disableUser(self, button: writeOutUser)  //self here I believe to be the cell 
    }


}

视图控制器:

class UserDetailTableViewController : UIViewController, UserCellDelegate {
    override func viewDidLoad() {
      super.viewDidLoad()
      let userCell = UserCell()
      userCell.delegate = self
    }

    func disableUser(cell: UserCell, button: UIButton) {
      print("VC: User Disabled")
    }
}

这里的问题是,我的ViewController中的disableUser函数永远不会被调用。 我究竟做错了什么?

最好的方法是什么?

我已经提到了SO批准的答案 ,这就是我所遵循的,但没有运气。 任何帮助将不胜感激。 谢谢!!

你应该在cellForRowAtIndexPath设置你的单元格的delegate 。正如@vadian所说,在viewDidLoad中你不应该使用默认的初始化程序来初始化你的单元格,并且在viewDidLoad ,你的单元格的委托是nil。

使用init(style:reuseIdentifier)初始化您的单元格,或者在行方法的单元格中设置委托,因为无论如何您将初始化该方法中的单元格。

当你这样做时:

let userCell = UserCell()
userCell.delegate = self

您设置的委托userCell的, 只有委托userCell 我确定表视图中显示的表视图单元格不是 userCell

因此,您应该设置实际要在表视图中显示的单元格的委托,而不是设置userCell的委托。 创建要在表视图中显示的新单元格的最可能位置是tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath)方法。

在该方法中,您必须具有以下内容:

let cell = ...
// setting properties of cell using the model
return cell

您只需要在返回之前添加此行:

cell.delegate = self

在你的代码中, UserCell就像一个UIView 您忘记将userCell添加到当前控制器的视图中。 如果你想使用UITableViewCell ,更好的方法是使用UITableView。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM