2017-07-31 52 views
4

我寫了一個自定義UIView,我發現了一個奇怪的問題。我認爲這是關係到一個非常基本的概念,但我只是不明白,感嘆.....不能在屬性初始值設定項內使用實例成員

class ArrowView: UIView { 

    override func draw(_ rect: CGRect) { 

     let arrowPath = UIBezierPath.bezierPathWithArrowFromPoint(startPoint: CGPoint(x:bounds.size.width/2,y:bounds.size.height/3), endPoint: CGPoint(x:bounds.size.width/2, y:bounds.size.height/3*2), tailWidth: 8, headWidth: 24, headLength: 18) 

     let fillColor = UIColor(red: 0.00, green: 0.59, blue: 1.0, alpha: 1.0) 
     fillColor.setFill() 
     arrowPath.fill() 
    } 
} 

此代碼工作正常,但如果我抓住這條線了覆蓋繪製函數它不編譯。錯誤說我不能使用邊界屬性。

let arrowPath = UIBezierPath.bezierPathWithArrowFromPoint(startPoint: CGPoint(x:bounds.size.width/2,y:bounds.size.height/3), endPoint: CGPoint(x:bounds.size.width/2, y:bounds.size.height/3*2), tailWidth: 8, headWidth: 24, headLength: 18) 

Cannot use instance member 'bounds' within property initializer; property initializers run before 'self' is available

我不不明白,爲什麼我不能用這個界定出FUNC的畫

+0

的可能的複製[錯誤:不能使用實例成員屬性初始化中 - 斯威夫特3](https://stackoverflow.com/questions/40710909/error-cannot-use-instance-member-within-property- initializer-swift-3) – Filburt

+0

您可以使用計算屬性[計算屬性示例](https://stackoverflow.com/a/39986404/6689101)來解決此問題。 – zombie

回答

7

所以,如果我們解碼你能弄清楚什麼是錯的錯誤消息。它說property initializers run before self is available所以我們需要調整我們正在做的事情,因爲我們的屬性取決於屬於自己的範圍。讓我們嘗試一個懶惰的變量。你不能在let中使用邊界,因爲當它屬於self時它不存在。所以在初始階段,自我還沒有完成。但是如果你使用一個懶惰的var,那麼當你需要的時候自己和它的屬性邊界就會準備好。

lazy var arrowPath = UIBezierPath.bezierPathWithArrowFromPoint(startPoint: CGPoint(x: self.bounds.size.width/2,y: self.bounds.size.height/3), endPoint: CGPoint(x: self.bounds.size.width/2, y: self.bounds.size.height/3*2), tailWidth: 8, headWidth: 24, headLength: 18) 
相關問題