最近,我对addTarget()在cellForRowAtIndexPath中使用UITableViewCell表示怀疑。我也渴望知道从UITableViewCell收听按钮事件的最佳实践是什么。
当我看到我没有办法注销添加到addTarget中的UIButton中的UITableViewCell侦听器时,我的困惑就开始了:
cellForRowAtIndexPath代码
cell.button.addTarget(self, action: "buttonClicked:", forControlEvents: UIControlEvents.TouchUpInside)上面的代码将一个侦听器注册到驻留在UIButton中的UITableViewCell,但是我看到没有关于注销它们的引用。我不确定这个过程是自动的还是非自动的(对于addTarget机制),我也没有在Apple中找到这样的引用(至少我已经搜索过了)。
所以,我的问题是,addTarget to UITableViewCell按钮是否适合使用?当视图控制器消失时,它们是否都去寄存器了?
或者,如果我使用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)
}如对此有任何建议,将不胜感激。
发布于 2015-08-13 06:05:37
传递给addTarget的目标不被保留。使用它是安全的;您不需要“取消注册”(或删除)目标。这是控制操作的标准机制(如按下按钮),您应该使用它(相对于通知)。
https://stackoverflow.com/questions/31980515
复制相似问题