CAShapeLayer 没有在 uiview 中正确居中

CAShapeLayer isn't centering in a uiview correctly

我试图将 CAShapeLayer 置于黑框的中心,但由于某种原因,形状总是绘制在框上方,如下所示:

这是我用来画圆的代码:

var pulsatingLayer: CAShapeLayer!
let shapeLayer = CAShapeLayer()
    
let timerLabel: UILabel = {
        let label = UILabel()
        label.textAlignment = .center
        if UIScreen.main.bounds.width > 414 {
            label.font = UIFont.systemFont(ofSize: 26, weight: .semibold)
        }
        else {
            label.font = UIFont.systemFont(ofSize: 37, weight: .semibold)
        }
        
        label.textColor = .white
        return label
}()
override func viewDidLoad() {
        super.viewDidLoad()
        
        let circularPath = UIBezierPath(arcCenter: .zero, radius: 35, startAngle: -CGFloat.pi / 2, endAngle: 3 * CGFloat.pi / 2, clockwise: true)

        // timerContainer is the black box
        
        pulsatingLayer = CAShapeLayer()
        pulsatingLayer.path = circularPath.cgPath
        pulsatingLayer.strokeColor = UIColor.clear.cgColor
        pulsatingLayer.lineWidth = 5
        pulsatingLayer.fillColor = UIColor.magenta.cgColor
        pulsatingLayer.position = timerContainer.center
        view.layer.addSublayer(pulsatingLayer)
        
        let trackLayer = CAShapeLayer()
        trackLayer.path = circularPath.cgPath
        trackLayer.strokeColor = UIColor.lightGray.cgColor
        trackLayer.lineWidth = 5
        trackLayer.fillColor = timerContainer.backgroundColor?.cgColor
        trackLayer.position = timerContainer.center
        view.layer.addSublayer(trackLayer)
        
        shapeLayer.path = circularPath.cgPath
        shapeLayer.strokeColor = UIColor.red.cgColor
        shapeLayer.lineWidth = 5
        shapeLayer.fillColor = timerContainer.backgroundColor?.cgColor
        shapeLayer.strokeEnd = 0
        shapeLayer.lineCap = .round
        shapeLayer.position = timerContainer.center
        view.layer.addSublayer(shapeLayer)
        
        view.addSubview(timerLabel)
        timerLabel.frame = CGRect(x: 0, y: 0, width: timerContainer.bounds.width, height: timerContainer.bounds.height)
        timerLabel.center = timerContainer.center
        
        
}

为什么圆没有以黑色视图为中心?

您需要在viewDidLayoutSubviews()

中设置位置
     timerContainer.layer.addSublayer(pulsatingLayer)
     timerContainer.layer.addSublayer(trackLayer)
     timerContainer.layer.addSublayer(shapeLayer)