2017-04-19 95 views
1

我目前正在爲我正在處理的應用程序製作自定義的UIView類,並且它要求您傳遞一個將在UIView的。我需要做的就是將函數傳遞給init()函數,並將其存儲起來,以便稍後調用它。我目前正在使用的代碼如下所示:將函數傳遞給變量以便稍後可以調用

class CustomUIView: UIView { 

    private var _tapListener : Void; 

    init (tapListener:() -> Void){ 
     //Attempt to set _tapListener variable as tap listener does not work :(
     _tapListener = tapListener(); 
     //Right now it just executes the function :(
     let listener = UITapGestureRecognizer(target: self, action: #selector(callFunction)); 
     self.addGestureRecognizer(listener) 
    } 

    required init?(coder aDecoder: NSCoder) { 
     fatalError("init(coder:) has not been implemented") 
    } 

    func callFunction() { 
     //Call the function here 
     _tapListener(); 
    } 
} 

如何完成我在此嘗試完成的操作?

任何及所有的幫助感激

+0

因爲類型你的'private var _tapListener'是錯誤的。 – matt

回答

1

考慮使用瓶蓋:

typealias tapListenerClosure =() -> Void 

class CustomUIView: UIView { 

    var tapClosure: tapListenerClosure 

    init (tap: @escaping tapListenerClosure) { 
     self.tapClosure = tap 
     super.init(.... 
     let listener = UITapGestureRecognizer(target: self, action: #selector(callFunction)); 
     self.addGestureRecognizer(listener) 
    } 

    required init?(coder aDecoder: NSCoder) { 
     fatalError("init(coder:) has not been implemented") 
    } 

    func callFunction() { 
     //Call the function here 
     self.tapClosure() 
    } 
} 
+2

您的_tapListener簽名不正確。它有Void類型。 – Brandon

+0

@Brandon謝謝你指出。編輯它並刪除未使用的伊娃。 – janusbalatbat

+0

這是一個非常好的和詳細的答案。謝謝! –

2

就以同樣的方式作爲參數的實例變量定義到init

private var _tapListener:() -> Void 
+0

這是一個非常簡單的解決方案!看起來我有一些閱讀關於真正封閉的事情。 –