【问题标题】:BezierPath sublayer does not wrap around the whole UIViewBezierPath 子层不环绕整个 UIView
【发布时间】:2021-10-02 01:24:24
【问题描述】:

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

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

这是左边

这是右边

这是我在 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)

【问题讨论】:

  • 关闭路径?
  • 在 viewDidLayoutSubview 方法中也加入这一行:dottedBorder.frame = myview.bounds
  • @ElTomato 关闭路径是什么意思?
  • @RajaKishan 不,仍然没有覆盖整个视图
  • @infiniteObj 请参阅UIBezierpath 的文档。

标签: ios swift uiview uibezierpath cashapelayer


【解决方案1】:

假设您使用的是自动布局,则不应依赖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
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-12-04
    • 1970-01-01
    • 2019-07-30
    • 2013-01-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多