2011-03-03 32 views
12

我使用UIImageView的UIButtons一大堆。所以,我創建了一個自定義類來永久結婚這兩件事情,讓事情變得更簡單。這一切運作良好,直到我決定實施 - (id)initWithObject:(AUIImageViewButton *)imageViewButton。如何獲得UIButton Target,Action和Control事件?

顯然我需要從傳遞的imageViewButton對象中複製所有相關屬性。 UIImageView完全沒有問題。像這樣的東西與它涉及:

imageview = [[UIImageView alloc] initWithFrame:imageViewButton.imageview.frame];  // Copy all relevant data from the source's imageview 
[imagebutton.imageview setBackgroundColor:imageViewButton.imageview.backgroundColor]; // 
[imagebutton.imageview setImage:imageViewButton.imageview.image];      // 

大部分按鈕的東西也一應俱全:

button = [UIButton buttonWithType:imageViewButton.button.buttonType];     // Copy all relevant data from the source's button 
button.frame = imageViewButton.imageview.frame;           // 
[button setTitle:imageViewButton.button.titleLabel.text forState:UIControlStateNormal]; // 
button.tag = imageViewButton.button.tag;            // 

我有一個小麻煩搞清楚如何獲取所有數據的addTarget:動作:forControlEvents方法。

看看文檔,我可以看到我可能能夠使用UIControl的allControlEvents和allTargets方法。我現在將深入研究,看看我可以付出多少麻煩。我不確定的是行動。

任何人都可以給我一個正確的方向推?

感謝,

-Martin

+0

只是檢查,你知道UIButton支持背景圖像(標題文本顯示在頂部)和圖像(沒有標題文本顯示)?你需要什麼UIImageView的功能? – Bogatyr

回答

31

UIControl的allTargetsallControlEvents是開始的方式。拼圖的最後一塊是actionsForTarget:forControlEvent:,爲每個目標和事件調用一次。

+0

啊!它就在那裏!就在我的面前!感謝您指出。 –

19

顯示如何遍歷按鈕的目標並在另一個按鈕上創建選擇器的副本。具體的例子就是touchupinside事件,但這通常是我所用的。

for (id target in button.allTargets) { 
    NSArray *actions = [button actionsForTarget:target 
             forControlEvent:UIControlEventTouchUpInside]; 
    for (NSString *action in actions) { 
      [newButton addTarget:target action:NSSelectorFromString(action) forControlEvents:UIControlEventTouchUpInside]; 
    } 
} 
0

我用這個分配一個新的人之前,以消除任何可能的不想要的目標/行動:

if let action = button.actions(forTarget: target, forControlEvent: .touchUpInside)?.first 
{ 
    button.removeTarget(target, action: NSSelectorFromString(action), for: .touchUpInside) 
} 

,或者如果你真的要刪除所有動作:

if let actions = button.actions(forTarget: target, forControlEvent: .touchUpInside) 
{ 
    for action in actions 
    { 
     button.removeTarget(target, action: NSSelectorFromString(action), for: .touchUpInside) 
    } 
}