2016-11-18 3 views
2

ターゲットをUIButtonに追加しようとしていますが、ネストされた関数をアクションとして使用しようとするとエラーが発生します。`UIButton`のアクションとしてネストされた関数を使用します。

は、ここに私のコードです:

func createAddView() { 
    let addButton = UIButton() 

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

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

私にこの警告与えている:私は削除する必要があるので、私は'createAddView'functionにネストされる'remove'機能を必要とする

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

を'createAddView '関数で作成されている他のUIViewをフェードアウトします。

私はこれをどのように行うことができますか?

+1

ターゲットとして入れ子関数を使用することはできません:http://stackoverflow.com/questions/29802074/nested-function-selector-in-swift-for-testing –

+0

'func remove(送信側:UIButton)'を外側に移動します。あなたの '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 removeがある原因はfunc createAddViewブロック内にのみ存在します。 を複数のUIControlに追加することに制限はありません。したがって、クラスブロック内にfunc removeを宣言し、新しいボタンを作成するたびに#selectorとして追加することができます。

関連する問題