[英]UIView frame center in IBOutlet initialization is incorrect
我有一个进度条,应该在视图的中心渲染,但是由于“自动布局”而最终偏离中心。
class ProgressView: UIView {
private let progressLayer: CAShapeLayer = CAShapeLayer()
private var progressLabel: UILabel
required init?(coder aDecoder: NSCoder) {
progressLabel = UILabel()
super.init(coder: aDecoder)
createProgressLayer()
createLabel()
}
override init(frame: CGRect) {
progressLabel = UILabel()
super.init(frame: frame)
createProgressLayer()
createLabel()
}
private func createProgressLayer() {
let startAngle = CGFloat(3*M_PI_2)
let endAngle = CGFloat(M_PI * 2 + 3*M_PI_2)
let centerPoint = CGPointMake(CGRectGetWidth(bounds)/2, CGRectGetHeight(bounds)/2)
let gradientMaskLayer = gradientMask()
progressLayer.path = UIBezierPath(arcCenter:centerPoint, radius: CGRectGetWidth(frame)/2-8, startAngle:startAngle, endAngle:endAngle, clockwise: true).CGPath
progressLayer.backgroundColor = UIColor.clearColor().CGColor
progressLayer.fillColor = nil
progressLayer.strokeColor = UIColor.blackColor().CGColor
progressLayer.lineWidth = 4.0
progressLayer.strokeStart = 0.0
progressLayer.strokeEnd = 0.0
gradientMaskLayer.mask = progressLayer
layer.addSublayer(gradientMaskLayer)
}
func animateProgressView() {
progressLayer.strokeEnd = 0.0
let animation = CABasicAnimation(keyPath: "strokeEnd")
animation.fromValue = CGFloat(0.0)
animation.toValue = CGFloat(1.0)
animation.duration = 2.0
animation.delegate = self
animation.removedOnCompletion = false
animation.additive = true
animation.fillMode = kCAFillModeForwards
progressLayer.addAnimation(animation, forKey: "strokeEnd")
}
}
该代码如下:
class MainPageController: UIViewController {
@IBOutlet var progressView : ProgressView!
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewDidLayoutSubviews() {
progressView.animateProgressView()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
并最终使圆偏离中心。 如果我手动编辑圆心,则右侧和底部的条似乎已被切除。 如果我关闭自动版式,则效果很好。 我究竟做错了什么?
故事板:
感谢您从情节提要中发布约束,我现在可以看到是什么原因造成的。
ProgessView设置有两个约束,一个约束使其保持正方形,另一个约束使其高度为视图高度的1/3。 这意味着在情节提要中看到的视图大小与设备上的视图大小不同。
从情节init?(coder aDecoder: NSCoder)
板加载视图时会调用init?(coder aDecoder: NSCoder)
。 它在自动版式运行之前被调用,因此您获得的bounds
和frame
的值基于情节提要中200x200的大小。 然后运行“自动布局”,并确定手机(看起来像iPhone 6)的尺寸应为222x222。 根据屏幕快照,您似乎在进度视图的右侧和底部大约有22pt的额外空间。
您要做的是在“自动版式”将视图设置为适当的大小后,调整进度层的大小。 最好的方法是通过从createProgressLayer
移动一些行在layoutSubviews
func layoutSubviews() {
let startAngle = CGFloat(3*M_PI_2)
let endAngle = CGFloat(M_PI * 2 + 3*M_PI_2)
let centerPoint = CGPointMake(bounds.width/2, bounds.height/2)
progressLayer.path = UIBezierPath(arcCenter:centerPoint, radius: frame.width/2-8, startAngle:startAngle, endAngle:endAngle, clockwise: true).CGPath
}
在Interface Builder中,将Progress View的内容模式更改为重绘,并覆盖drawRect并从此处调用createProgressLayer。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.