如何在UIView-Swift中将CAShapeLayer居中放置?

时间:2018-09-03 20:33:20

标签: ios swift cashapelayer

我正在尝试使用UIViewController创建一个加载进度圈弹出窗口。我在尝试使UIView成为父视图的子视图的UIView时遇到问题。有人可以请教吗?

我正在尝试使用UIViewController创建一个加载进度圈弹出窗口。我在尝试使UIView成为父视图的子视图的UIView时遇到问题。有人可以请教吗?

enter image description here

 let shapeLayer = CAShapeLayer()

let percentageLabel: UILabel = {
    let label = UILabel()
    label.text = "Start"
    label.textAlignment = .center
    label.font = UIFont.boldSystemFont(ofSize: 32)
    return label
}()


 override func viewDidLoad() {
    super.viewDidLoad()

    createObserver()

    self.poUpOutlet.addSubview(percentageLabel)
    percentageLabel.frame = CGRect(x: 0, y: 0, width: 100, height: 100)
    percentageLabel.center = self.poUpOutlet.center

    let trackLayer = CAShapeLayer()

    let circularPath = UIBezierPath(arcCenter: .zero, radius: 50, startAngle: 0, endAngle: 2 * CGFloat.pi, clockwise: true)
    trackLayer.path = circularPath.cgPath

    trackLayer.strokeColor = UIColor.lightGray.cgColor
    trackLayer.lineWidth = 10
    trackLayer.fillColor = UIColor.clear.cgColor
    trackLayer.lineCap = kCALineCapRound
    trackLayer.position = self.poUpOutlet.center

    self.poUpOutlet.layer.addSublayer(trackLayer)

    shapeLayer.path = circularPath.cgPath

    shapeLayer.strokeColor = UIColor.red.cgColor
    shapeLayer.lineWidth = 10
    shapeLayer.fillColor = UIColor.clear.cgColor
    shapeLayer.lineCap = kCALineCapRound
    shapeLayer.position = self.poUpOutlet.center

    shapeLayer.transform = CATransform3DMakeRotation(-CGFloat.pi / 2, 0, 0, 1)

    shapeLayer.strokeEnd = 0

    self.poUpOutlet.layer.addSublayer(shapeLayer)
}

1 个答案:

答案 0 :(得分:2)

替换3个出现的

self.poUpOutlet.center

在代码中使用:

self.poUpOutlet.convert(self.poUpOutlet.center, from: self.poUpOutlet.superview)

然后它应该工作。