【发布时间】:2019-12-12 23:21:13
【问题描述】:
我正在尝试定位一个圆形进度条,但我经常失败。我想我不理解框架、视图和边界的概念。我发现这篇关于堆栈溢出的帖子准确地向我展示了如何构建一个圆形进度条。
但是,在帖子中,使用 CGRect(x: 100, y: 100, width: 100, height: 100) 创建了一个 circleView 作为 UIView
在我的情况下,手动设置 x 和 y 坐标是一个很大的问题。所以 circleView 必须在它的父视图的中心。
这是我的视图层次结构:
view -> view2ForHomeController -> middleView -> circleView
所以一切都使用自动布局定位。这是问题所在:circleView 正在正确添加,它将自身定位在我指定的 x 和 y 值,但我如何指定 middleView 中心的 x 和 y 值。我尝试了以下方法,但中心值返回为 0.0、0.0。
self.view.addSubview(self.view2ForHomeController)
self.view2ForHomeController.fillSuperview()
let xPosition = self.view2ForHomeController.middleView.frame.midX
let yPostion = self.view2ForHomeController.middleView.frame.midY
print(xPosition) // ------- PRINTS ZERO
print(yPostion) // ------- PRINTS ZERO
let circle = UIView(frame: CGRect(x: xPosition, y: yPostion, width: 100, height: 100))
circle.backgroundColor = UIColor.green
self.view2ForHomeController.middleView.addSubview(circle)
var progressCircle = CAShapeLayer()
progressCircle.frame = self.view.bounds
let lineWidth: CGFloat = 10
let rectFofOval = CGRect(x: lineWidth / 2, y: lineWidth / 2, width: circle.bounds.width - lineWidth, height: circle.bounds.height - lineWidth)
let circlePath = UIBezierPath(ovalIn: rectFofOval)
progressCircle = CAShapeLayer ()
progressCircle.path = circlePath.cgPath
progressCircle.strokeColor = UIColor.white.cgColor
progressCircle.fillColor = UIColor.clear.cgColor
progressCircle.lineWidth = 10.0
progressCircle.frame = self.view.bounds
progressCircle.lineCap = CAShapeLayerLineCap(rawValue: "round")
circle.layer.addSublayer(progressCircle)
circle.transform = circle.transform.rotated(by: CGFloat.pi/2)
let animation = CABasicAnimation(keyPath: "strokeEnd")
animation.fromValue = 0
animation.toValue = 1.1
animation.duration = 1
animation.repeatCount = MAXFLOAT
animation.fillMode = CAMediaTimingFillMode.forwards
animation.isRemovedOnCompletion = false
animation.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeIn)
progressCircle.add(animation, forKey: nil)
【问题讨论】: