UIBezierPath addLine:绘制时长度错误

UIBezierPath addLine: wrong length uppon draw

给出的是一个 UIBezierPath,它应该是 "dashed" 并作为子层添加到视图中:

    let shapeLayer = CAShapeLayer()
    shapeLayer.strokeColor = UIColor.blue.cgColor
    shapeLayer.lineWidth = 0.8
    shapeLayer.lineDashPattern = [7, 7]
    shapeLayer.fillColor = UIColor.clear.cgColor

    let path = CGMutablePath()
    path.move(to: .zero)
    path.addLine(to: CGPoint(x: view.bounds.width, y: 0)) // HERE IS THE PROBLEM
    shapeLayer.path = path
    view.layer.addSublayer(shapeLayer)
    view.backgroundColor = .yellow

问题是,虚线不等于 "view" 的宽度:

黄色是视图本身的背景色。虚线是创建的UIBezierPath。

非常感谢您的帮助。

如果有人遇到这个问题:

正如@rmaddy 所说,问题是在 viewWillAppear 中调用了这个函数。大小尚未正确初始化的地方。 在 viewDidAppear 中调用相同的函数解决了问题。