OStack程序员社区-中国程序员成长平台

标题: ios - 如何在 View 的框架上添加虚线边框而不是边界 [Swift] [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-12 14:58
标题: ios - 如何在 View 的框架上添加虚线边框而不是边界 [Swift]

我正在尝试在 View 上添加一个虚线边框,该边框将始终位于 View 的框架上,而不是在它的 bound 上。

我的代码:

func addDashedBorder() {

    let color = UIColor.red.cgColor
    shapeLayer = CAShapeLayer()
    let frameSize = self.bounds.size
    let shapeRect = CGRect(x:0 , y: 0, width: frameSize.width, height: frameSize.height)

    shapeLayer.frame = shapeRect
    shapeLayer.position = CGPoint(x: frameSize.width/2, y: frameSize.height/2)
    shapeLayer.fillColor = UIColor.clear.cgColor
    shapeLayer.strokeColor = color
    shapeLayer.lineWidth = 2
    shapeLayer.lineJoin = CAShapeLayerLineJoin.round
    shapeLayer.lineDashPattern = [6,3]
    shapeLayer.path = UIBezierPath(roundedRect: self.frame, cornerRadius: 5).cgPath

    self.layer.addSublayer(shapeLayer)
}

结果
enter image description here

如果我们旋转 View ,我不想旋转 View 上的边框。 它应该表明它在 View 中占据了多少空间。

期待

enter image description here



Best Answer-推荐答案


您需要采取两个 View ,即内部 View 和外部 View 。内 View (旋转 View )应该在外 View 的 subview 中。两个 View 的框架必须相同。使用以下代码行 -

@IBOutlet weak var viewOuter: UIView! //static outer view
@IBOutlet weak var viewInner: UIView! // View that will be use for rotation

func addDashedBorder() {

    let color = UIColor.red.cgColor
    let shapeLayer = CAShapeLayer()
    let frameSize = viewInner.bounds.size
    let shapeRect = CGRect(x:0 , y: 0, width: frameSize.width, height: frameSize.height)
    shapeLayer.frame = shapeRect
    shapeLayer.position = CGPoint(x: frameSize.width/2, y: frameSize.height/2)
    shapeLayer.fillColor = UIColor.clear.cgColor
    shapeLayer.strokeColor = color
    shapeLayer.lineWidth = 2
    shapeLayer.lineJoin = kCALineJoinRound
    shapeLayer.lineDashPattern = [6,3]
    shapeLayer.path = UIBezierPath(roundedRect: viewInner.frame, cornerRadius: 5).cgPath
    self.viewOuter.layer.addSublayer(shapeLayer)

}

关于ios - 如何在 View 的框架上添加虚线边框而不是边界 [Swift],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52714622/






欢迎光临 OStack程序员社区-中国程序员成长平台 (https://ostack.cn/) Powered by Discuz! X3.4