2016-11-18 63 views
2

我試圖添加一個目標到我的UIButton,但是在嘗試使用嵌套函數作爲它的動作時得到一個錯誤。使用嵌套函數作爲`UIButton`的動作

這裏是我的代碼:

func createAddView() { 
    let addButton = UIButton() 

    func remove(sender: UIButton) { 
     print("Remove") 
    } 

    addButton.addTarget(self, action: #selector(remove(sender:)), for: .touchUpInside) 
} 

它給我這樣的警告:

warning: No method declared with Objective-C selector 'remove'. 

我需要'remove'函數嵌套在'createAddView'function,因爲我需要刪除並淡出正在創建的'createAddView'函數中的其他一些UIViews

任何人都知道我該怎麼做?

+1

你不能使用嵌套函數作爲目標:http://stackoverflow.com/questions/29802074/nested-function-selector-in-swift-for-testing –

+0

移動你的'func remove(sender:UIButton)'outside你的'createAddView()'並嘗試? – Joe

回答

0

因爲func remove是在createAddView()方法中創建的。

here's固定的代碼:

func createAddView() { 
    let view = UIView() //added for testing purposes 
    view.frame = CGRect(x: 0, y: 0, width: 320 , height: 640) //added for testing purposes 
    let addButton = UIButton() 
    addButton.frame = CGRect(x: 0, y: 0, width: 100, height: 50) //added for testing purposes 


    view.addSubview(addButton) 



    addButton.addTarget(self, action: #selector(remove(sender:)), for: .touchUpInside) 

} 

func remove(sender: UIButton) { 
    UIView.animate(withDuration: 0.3, delay: 0, options: UIViewAnimationOptions.allowUserInteraction, animations: {() -> Void in 
     print("Add") 
    }) {(Bool) -> Void in 
     print("Done") 
    } 
} 
1

你不能做到這一點,導致func removefunc createAddView塊只存在。 對多個UIControl添加一個#selector()沒有限制。因此,您可以在類塊中聲明func remove,並在每次創建新按鈕時將其添加爲#selector