2016-05-04 501 views
6

我得到一個函數作爲函數參數,並希望在#selector中設置它。 但我得到的錯誤信息:將函數傳遞給#selector

Argument of '#selector' cannot refer to a property 

我有以下功能:

private func addGestureRecognizerToItem(selector:() ->()) { 
     let labelGesture = UITapGestureRecognizer(target: self, action: #selector(selector)) 
     let imageGesture = UITapGestureRecognizer(target: self, action: #selector(selector)) 
     label.addGestureRecognizer(labelGesture) 
     imageView.addGestureRecognizer(imageGesture) 
} 

任何想法如何處理這個問題?

+0

不可能的,因爲目標是'self',你不能傳遞閉包'UIGestureRecognizer' –

回答

7

這個怎麼樣?

class ViewController: UIViewController { 

let label = UILabel() 
let imageView = UIImageView() 

override func viewDidLoad() { 
    super.viewDidLoad() 

    addGestureRecognizerToItem(#selector(test)) 
} 

func test() { 
} 

private func addGestureRecognizerToItem(selector: Selector) { 
    let labelGesture = UITapGestureRecognizer(target: self, action: selector) 
    let imageGesture = UITapGestureRecognizer(target: self, action: selector) 
    label.addGestureRecognizer(labelGesture) 
    imageView.addGestureRecognizer(imageGesture) 
} 

}

+0

Alots THX的你 –

0

這是不可能的,相反,您可以從您想要傳遞給另一個數據的第一個函數的返回中調用所需的函數。 而你的情況可能會根據你的要求而改變。