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.addTarget
到configureButton
:
configureButton(scanButton, action: "goToScanner", title: "Scan", pos: [36.0, 300])
我想傳遞一個閉合() ->()
,但沒有奏效。
我該如何解決這個問題?