2017-07-31 137 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) 
相关问题