如何在 UIView - Swift 中居中我的 CAShapeLayer?

How to centre my CAShapeLayer within UIView - Swift?

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

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

 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)
}

替换出现的 3 次

self.poUpOutlet.center

在您的代码中:

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

那么应该可以了。