2016-07-04 65 views
3

我有一個UIButton。我想使用相同的UIButton來執行多個操作。首先我以編程方式將動作設置爲按鈕。是否有可能在Swift中重寫UIButton的操作方法?

button1.addTarget(self, action: #selector(ViewController.function1), forControlEvents: .TouchUpInside) 

接下來,我想放棄該功能並希望添加其他操作。

button1.addTarget(self, action: #selector(ViewController.function2), forControlEvents: .TouchUpInside) 

是否有可能覆蓋按鈕的現有目標?

+0

它沒有前刪除所有以前的操作感覺使用多個addTarget到一個按鈕,高級推理是:「按鈕 - > IBAction,然後你在動作方法內部開發你的條件.. –

回答

3

你的建議不會覆蓋以前採取行動的情況下,但第二個動作增加,導致ViewController.function1ViewController.function2按鈕被調用。

您需要使用

button1.removeTarget(self, action: #selector(ViewController.function1), forControlEvents: .AllEvents)

添加新的人之前先移除目標之前的操作或添加新的

button1.removeTarget(nil, action: nil, forControlEvents: .AllEvents)

4

您需要添加新的其他人會引起所採取的行動之前,移除目標之前的動作來觸發

button1.removeTarget(self, action: #selector(ViewController.function1), forControlEvents: .AllEvents) 
0

當你添加的目標,你可以用你的按鈕removeTarget方法將其刪除:

func removeTarget(_ target: AnyObject?, 
     action action: Selector, 
forControlEvents controlEvents: UIControlEvents) 

編輯:見@Rohit KP的例如使用的答案。然而,你可能要考慮使用別的東西」 .AllEvents」這取決於你所需要的。

2

我recommande你創建一個包裝函數。由於添加/刪除動態目標可能會導致死鎖。

所以你可能必須創建一個將被永遠調用的函數,並做你的東西:

@IBOutlet func myWrapper(sender : AnyObject?) { 

if (conditionA) { 
    // do stuff A 
} else { 
    // do stuff B 
} 
} 
+0

你能提供你正在談論的僵局情況嗎? –

+1

這是最明智的答案,並符合Apple框架。 –

+0

不,我不能,因爲我不知道你的代碼,我的意思是你可能處於一個你刪除所有目標的狀態,或者添加2個目標。這確實很難保證。有一個if-else語句是實現您的目標的更安全的方式(和可調試的方式) – CZ54

相關問題