2015-05-31 92 views
2

我注意到我有很多功能來動態添加按鈕在我的一個視圖控制器中,這顯然違背了DRY原則。如何動態添加一個動作到一個UIButton

爲了解決這個問題,我寫了一擊,一切configureButton功能:

func configureButton (button: UIButton, action: String, title: String, pos: [CGFloat]) { 
    button.addTarget(self, action: action, 
      forControlEvents: UIControlEvents.TouchUpInside) 
    //^throws an error 

    // button.addTarget(self, action: "goToScanner", 
    //  forControlEvents: UIControlEvents.TouchUpInside) 

    /* configure everything else */   

    self.view.addSubview(button) 
} 

當我有無數個不同的功能,我只是在他們每個人寫的東西一樣

button.addTarget(self, action: "goToScanner", // <-- note the string 
     forControlEvents: UIControlEvents.TouchUpInside) 

,其中"goToScanner"是我想要在水龍頭上調用的功能。

我希望能夠動態地將操作參數爲button.addTargetconfigureButton

configureButton(scanButton, action: "goToScanner", title: "Scan", pos: [36.0, 300]) 

我想傳遞一個閉合() ->(),但沒有奏效。

我該如何解決這個問題?

回答

2

你的方法應該是

func configureButton (button: UIButton, action: Selector, title: String, pos: [CGFloat]) 

注意它如何使用Selector而不是String

這是因爲雨燕沒有在實施Selector建,你傳遞一個字符串,字符串文字的類型推斷爲Selector(隨便怎麼樣都進入了一些文本將作爲既是一個整數,浮點, NSNumber等)。