2014-11-23 67 views
2

我想初始化一個UIPanGestureRecognizer作爲UIViewController的屬性定義的一部分,這樣我就不必聲明它是可選的(因爲如果初始化僅在viewDidLoad中發生,我將不得不聲明它是可選的)。將UIGestureRecognizer初始化爲Swift中屬性定義的一部分?

以下兩次嘗試都失敗在編譯的時候(我使用的是最新版本的Xcode):

-- 1st attempt 
class TestController: UIViewController { 

    let panGestureRecognizer: UIPanGestureRecognizer 

    required init(coder: NSCoder) { 
     super.init(coder: coder) 
     panGestureRecognizer = UIPanGestureRecognizer( target: self, action: "handlePan:") 
     // fails with "Property 'self.panGestureRecognizer' not initialized at super.init call' or 
     // fails with "'self' used before super.init call' 
     // depending on the order of the two previous statements 
    } 
} 

-- 2st attempt 
class TestController: UIViewController { 

    let panGestureRecognizer = UIPanGestureRecognizer(target:self, action: "handlePan:") 
    // fails with "Type 'TestController ->() -> TestController!' does not conform to protocol 'AnyObject' 
} 

有另一種有效的方法,從而完成這項工作?

回答

7

問題是,您在self準備好之前將self作爲目標添加。

你可以創建手勢識別器,調用超級初始化,然後添加自己作爲目標,我認爲這將工作。

我個人傾向於將其設置爲lazy var而不是let。它保持封裝並節省你不得不覆蓋init方法。

+2

Thx。創建手勢識別器,調用超級初始化,然後添加自己作爲目標確實有效。 – Drux 2014-11-23 11:47:05