如何在视图的框架而不是边界上添加虚线边框 [Swift]

How to add dashed border on View's frame not on bounds [Swift]

我正在尝试在视图上添加一个虚线边框,该边框将始终位于视图的框架上,而不是在其绑定上。

我的代码:

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)
}

结果

如果我们旋转视图,我不想旋转视图上的边框。 它应该表明有多少 space 它正在被观看。

预期

你需要有两个视图,即内部视图和外部视图。内视图(旋转视图)应该在外视图的子视图中。两个视图的框架必须相同。使用以下代码行 -

@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)

}