【发布时间】:2016-10-12 15:03:07
【问题描述】:
我正在尝试实现委托方式,以便对从我的 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 Approved Answer Here,这也是我所遵循的,但没有运气。 任何帮助将不胜感激。谢谢!!
【问题讨论】:
-
看起来您的委托在 vieDidLoad 中为零。你应该在 cellForRow 方法中设置 delagate
-
您不能使用默认初始化程序
()初始化UITableViewCell的实例。你必须调用指定的初始化器init(style:reuseIdentifier:)。在 Swift 中,使用回调闭包比使用委托模式更方便。 -
@TejaNandamuri:成功了!我忽略了它是一个 tableViewCell 的事实 :-(
-
我找不到这样的代码 func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 你在哪里实现 UITableViewDataSource
标签: ios iphone swift delegates