BezierPath 子层不会环绕整个 UIView

问题描述

我目前正在尝试在我的 UIView 周围制作虚线边框。我参考了以前的帖子:Dashed line border around UIView

UIView 左侧有红色虚线,但右侧没有边缘。

Left side

这是左边

Right side

这是右侧

这是我在 viewDidLoad 中执行的代码

myview.backgroundColor = UIColor.lightGray
myview.layer.cornerRadius = 4

let dottedBorder = CAShapeLayer()
dottedBorder.strokeColor = UIColor.red.cgColor
dottedBorder.lineDashPattern = [4,4]
dottedBorder.frame = myview.bounds
dottedBorder.fillColor = nil
dottedBorder.path = UIBezierPath(roundedRect: myview.bounds,byRoundingCorners: .allCorners,cornerRadii: CGSize(width: 4,height: 4)).cgPath
        
myview.layer.addSublayer(dottedBorder)

解决方法

假设您使用的是自动布局,您不应该依赖于 viewDidLoad 内的视图大小,因为它通常等于您的故事板设备大小(选择的是 SB 编辑器),而不是真正的设备大小。

无论如何,将来可能会改变。所有依赖于 frame/bounds 的计算都需要在 viewDidLayoutSubviews 内完成。像这样:

private let dottedBorder = CAShapeLayer()

override func viewDidLoad() {
    super.viewDidLoad()
    
    dottedBorder.strokeColor = UIColor.red.cgColor
    dottedBorder.lineDashPattern = [4,4]
    dottedBorder.fillColor = nil
    myview.layer.addSublayer(dottedBorder)
}

override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()

    dottedBorder.frame = myview.bounds
    dottedBorder.path = UIBezierPath(roundedRect: myview.bounds,byRoundingCorners: .allCorners,cornerRadii: CGSize(width: 4,height: 4)).cgPath
}