是否有可能在Swift中重写UIButton的操作方法?
我有一个UIButton
。我想使用相同的UIButton
来执行多个操作。首先我以编程方式将动作设置为按钮。是否有可能在Swift中重写UIButton的操作方法?
button1.addTarget(self, action: #selector(ViewController.function1), forControlEvents: .TouchUpInside)
接下来,我想放弃该功能并希望添加其他操作。
button1.addTarget(self, action: #selector(ViewController.function2), forControlEvents: .TouchUpInside)
是否有可能覆盖按钮的现有目标?
你的建议不会覆盖以前采取行动的情况下,但第二个动作增加,导致ViewController.function1
和ViewController.function2
按钮被调用。
您需要使用
button1.removeTarget(self, action: #selector(ViewController.function1), forControlEvents: .AllEvents)
添加新的人之前先移除目标之前的操作或添加新的
button1.removeTarget(nil, action: nil, forControlEvents: .AllEvents)
您需要添加新的其他人会引起所采取的行动之前,移除目标之前的动作来触发
button1.removeTarget(self, action: #selector(ViewController.function1), forControlEvents: .AllEvents)
当你添加的目标,你可以用你的按钮removeTarget方法将其删除:
func removeTarget(_ target: AnyObject?,
action action: Selector,
forControlEvents controlEvents: UIControlEvents)
编辑:见@Rohit KP的例如使用的答案。然而,你可能要考虑使用别的东西” .AllEvents”这取决于你所需要的。
我recommande你创建一个包装函数。由于添加/删除动态目标可能会导致死锁。
所以你可能必须创建一个将被永远调用的函数,并做你的东西:
@IBOutlet func myWrapper(sender : AnyObject?) {
if (conditionA) {
// do stuff A
} else {
// do stuff B
}
}
你能提供你正在谈论的僵局情况吗? –
这是最明智的答案,并符合Apple框架。 –
不,我不能,因为我不知道你的代码,我的意思是你可能处于一个你删除所有目标的状态,或者添加2个目标。这确实很难保证。有一个if-else语句是实现您的目标的更安全的方式(和可调试的方式) – CZ54
它没有前删除所有以前的操作感觉使用多个addTarget到一个按钮,高级推理是:“按钮 - > IBAction,然后你在动作方法内部开发你的条件.. –