@IBDesignable UiView draw(_ rect: CGRect) 在 IB 中有效,但在设备上无效
@IBDesignable UiView draw(_ rect: CGRect) works in IB but not on device
我在作为 UIControl 子类的绘制矩形函数中有一个圆圈进度。 Swift3,Xcode8.
看起来像这样:
override func draw(_ rect: CGRect) {
super.draw(rect)
guard let ctx = UIGraphicsGetCurrentContext() else {
return
}
let center = CGPoint(x:rect.size.width/2.0,y:rect.size.height/2.0)
ctx.setStrokeColor(UIColor.cyan.cgColor)
ctx.setLineWidth(40)
ctx.setLineCap(.round)
ctx.addArc(center: center, radius: radius, startAngle: 0, endAngle: CGFloat(M_PI * 2), clockwise: true)
ctx.drawPath(using: .stroke)
}
正在以编程方式将此视图添加到 @IBDesignable UIViewSubclass
override func awakeFromNib() {
super.awakeFromNib()
self.backgroundColor = UIColor.yellow
self.circleTest = TestCircle(frame: self.bounds)
self.addSubview(circleTest!)
setupConstraints() //pins subview to edges of self.
}
我哪里做错了?
问题是 radius
的设置。在评论中你指出你在 init
中设置它,并且你显然必须允许框架中的后续更改(尤其是在使用自动布局时),因此你可以移动 radius
的分配进入 draw(_:)
(or, if you weren't using draw(_:)
, but rather CAShapeLayer
or the like, you could do it in layoutSubviews()
).
我在作为 UIControl 子类的绘制矩形函数中有一个圆圈进度。 Swift3,Xcode8.
看起来像这样:
override func draw(_ rect: CGRect) {
super.draw(rect)
guard let ctx = UIGraphicsGetCurrentContext() else {
return
}
let center = CGPoint(x:rect.size.width/2.0,y:rect.size.height/2.0)
ctx.setStrokeColor(UIColor.cyan.cgColor)
ctx.setLineWidth(40)
ctx.setLineCap(.round)
ctx.addArc(center: center, radius: radius, startAngle: 0, endAngle: CGFloat(M_PI * 2), clockwise: true)
ctx.drawPath(using: .stroke)
}
正在以编程方式将此视图添加到 @IBDesignable UIViewSubclass
override func awakeFromNib() {
super.awakeFromNib()
self.backgroundColor = UIColor.yellow
self.circleTest = TestCircle(frame: self.bounds)
self.addSubview(circleTest!)
setupConstraints() //pins subview to edges of self.
}
我哪里做错了?
问题是 radius
的设置。在评论中你指出你在 init
中设置它,并且你显然必须允许框架中的后续更改(尤其是在使用自动布局时),因此你可以移动 radius
的分配进入 draw(_:)
(or, if you weren't using draw(_:)
, but rather CAShapeLayer
or the like, you could do it in layoutSubviews()
).