最近我有点怀疑,在cellForRowAtIndexPath中使用 addTarget() 到 UITableViewCell 。我也很想知道从 UITableViewCell 监听按钮事件的最佳做法是什么。
当我看到我无法取消注册添加到 UIButton 驻留在 UITableViewCell 中的addTarget侦听器时,我的困惑开始了:
cellForRowAtIndexPath的代码:
cell.button.addTarget(self, action: "buttonClicked:", forControlEvents: UIControlEvents.TouchUpInside)
上面的代码向驻留在 UITableViewCell 中的 UIButton 注册了一个侦听器,但我看到没有取消注册它们的参考。我不确定这个过程是否是自动的(对于 addTarget-mechanism),我还没有在 Apple doc 中找到任何这样的参考资料(至少到目前为止我已经搜索过)。
所以,我的问题是,使用 UITableViewCell 按钮的addTarget好用吗?当视图控制器消失时,它们是否都会取消注册?
或者,如果我使用 addObserver 会更好?
override func viewDidLoad()
{
super.viewDidLoad()
NSNotificationCenter.defaultCenter().addObserver(self, selector: "onCellButtonPressed:", name: "cellButtonPressed", object: nil)
}
func onCellButtonPressed(notification:NSNotification)
{
if let sender = notification.object as? UIButton
{
...
}
}
在 UITableViewCell 代码中:
@IBAction func onButtonPressed(sender: AnyObject)
{
NSNotificationCenter.defaultCenter().postNotificationName("cellButtonPressed", object: sender)
}
对此的任何建议,将不胜感激。