ios 不能在属性初始值设定项中使用实例成员
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/45423321/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Cannot use instance member within property initializer
提问by Billy
I have written a custom UIView
and I found a strange problem. I think this is related to a very fundamental concept but I just do not understand it, sigh.....
我写了一个自定义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()
}
}
this code works fine but if I have grabbed this line out of the override draw function it does not compile. The error says I can not use the bounds property.
这段代码工作正常,但如果我从覆盖绘制函数中提取了这条线,它就不会编译。错误说我不能使用 bounds 属性。
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
不能在属性初始值设定项中使用实例成员“边界”;属性初始值设定项在 'self' 可用之前运行
I don not understand why I cannot use this bounds out of the func draw
我不明白为什么我不能在 func draw 之外使用这个边界
回答by Ryan Poolos
So if we decode the error message you can figure out whats wrong. It says property initializers run before self is available
so we need to adjust what we're doing since our property depends on bounds which belongs to self. Lets try a lazy variable. You can't use bounds in a let because it doesn't exist when that property is created because it belongs to self. So at init self isn't complete yet. But if you use a lazy var, then self and its property bounds will be ready by the time you need it.
因此,如果我们对错误消息进行解码,您就可以找出问题所在。它说property initializers run before self is available
所以我们需要调整我们正在做的事情,因为我们的财产取决于属于自己的界限。让我们尝试一个惰性变量。您不能在 let 中使用边界,因为在创建该属性时它不存在,因为它属于 self。所以在 init self 还没有完成。但是如果你使用一个惰性变量,那么 self 和它的属性边界会在你需要的时候准备好。
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)