视图周围未对齐的边框

Misaligned border around the view

我正在尝试在视图周围创建边框。为此,我正在使用 UIBezierPath 创建一个与视图大小相同的层,并使用描边颜色创建另一个层。然后我将贝塞尔图层分配给描边颜色图层并将其作为子图层添加到视图中。

有没有人遇到过这个问题?

class ViewController: UIViewController {

  @IBOutlet weak var rectangleView: UIView!

  override func viewDidLoad() {
    super.viewDidLoad()

    let bezierLayer = CAShapeLayer()
    bezierLayer.bounds = rectangleView.frame
    bezierLayer.position = rectangleView.center
    bezierLayer.path = UIBezierPath(rect: rectangleView.bounds).cgPath

    let borderLayer = CAShapeLayer()
    borderLayer.bounds = rectangleView.frame
    borderLayer.position = rectangleView.center
    borderLayer.fillColor = UIColor.clear.cgColor
    borderLayer.strokeColor = UIColor.black.cgColor
    borderLayer.lineWidth = 1

    borderLayer.path = bezierLayer.path

    rectangleView.layer.addSublayer(borderLayer)
  }
}

如果有人想知道约束可能是错误的,这里是故事板配置:

我能够解决它,诀窍是像这样将边框实现放在 viewDidLayoutSubviews 中:

override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()

    rectangleView.layer.sublayers?.forEach {
      guard let layer = [=10=] as? CAShapeLayer else { return }
      layer.removeFromSuperlayer()
    }

    let bezierLayer = CAShapeLayer()
    bezierLayer.frame = rectangleView.bounds
    bezierLayer.path = UIBezierPath(rect: rectangleView.bounds).cgPath

    let borderLayer = CAShapeLayer()
    borderLayer.frame = rectangleView.bounds
    borderLayer.fillColor = UIColor.clear.cgColor
    borderLayer.strokeColor = UIColor.black.cgColor
    borderLayer.lineWidth = 1

    borderLayer.path = bezierLayer.path

    rectangleView.layer.addSublayer(borderLayer)
  }