我应该如何在UIView周围添加一条用VFL编码的虚线

时间:2015-10-21 15:32:25

标签: swift uiview cashapelayer

我只是想用VFL在一些视图编码周围画一条虚线。这是我的演示代码

var ZLDashLineLayerInView = "com.siamLian.ZLDashLineLayerInView"
extension UIView {

    convenience init(frame:CGRect = CGRectZero, lineDashPattern: [NSNumber], strokeColor: UIColor?, fillColor: UIColor? = UIColor.clearColor(), lineWidth: CGFloat = 1, roundingCorners: UIRectCorner = .AllCorners, cornerRadii: CGSize) {
        let ori_Method =  class_getInstanceMethod(UIView.self, "drawRect:")

        let my_Method = class_getInstanceMethod(UIView.self, "ZLDrawRect:");
        method_exchangeImplementations(ori_Method, my_Method)

        self.init(frame: frame)
        let shapeLayer = CAShapeLayer()
        shapeLayer.lineDashPattern = lineDashPattern
        shapeLayer.strokeColor = strokeColor?.CGColor
        shapeLayer.fillColor = fillColor?.CGColor
        shapeLayer.lineWidth = lineWidth

        let path = UIBezierPath(roundedRect: frame, byRoundingCorners: roundingCorners, cornerRadii: cornerRadii)
        shapeLayer.path = path.CGPath
        self.layer.addSublayer(shapeLayer)
        //objc_setAssociatedObject(self, &ZLDashLineLayerInView, shapeLayer, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
        //self.addObserver(self, forKeyPath: "bounds", options: NSKeyValueObservingOptions.New, context: nil)
        self.setNeedsDisplay()
    }
}
像这样的

init视图:

        let label = UILabel(frame: CGRectMake(0, 0, 0, 0), lineDashPattern: [NSNumber(integer: 7), NSNumber(integer: 7)], strokeColor: UIColor.redColor(), lineWidth: 1, cornerRadii: CGSizeMake(10, 0))
        label.text = "sssssssssssss"
        label.center = self.view.center
        self.view.addSubview(label)

        label.translatesAutoresizingMaskIntoConstraints = false
        self.view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-100-[label]-100-|", options: NSLayoutFormatOptions.AlignAllCenterX, metrics: nil, views: ["label" : label]))
        self.view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-100-[label]-100-|", options: NSLayoutFormatOptions.AlignAllCenterY, metrics: nil, views: ["label" : label]))

由于标签的框架,我使用错误的框架初始化shapelayer.path,所以何时应该更新shapelayer的路径?

注意: 我知道我可以自定义视图并覆盖func

func drawRect(_ rect: CGRect)

我不想要自定义视图,感谢任何答案

0 个答案:

没有答案