iOS添加CAShapeLayer未在运行时显示

时间:2017-07-22 18:13:38

标签: ios swift cashapelayer

我有一个文本字段,从故事板添加,尝试使用CAShapeLayer和BeizerPath在文本字段底部添加行

extension UITextField {

    func getLine() {
        let x1 = self.frame.origin.x
        let y = self.frame.origin.y + self.frame.size.height
        let start = CGPoint(x: x1, y: y)

        let x2 = self.frame.origin.x + self.frame.size.width
        let end = CGPoint(x: x2, y: y)

        print("\(start) \(end)")

        let path = UIBezierPath()
        path.move(to: start)
        path.addLine(to: end)

        let shapeLayer = CAShapeLayer()
        shapeLayer.path = path.cgPath
        shapeLayer.strokeColor = UIColor.black.cgColor
        shapeLayer.lineWidth = 1.0
        shapeLayer.fillColor = UIColor.clear.cgColor
        self.layer.addSublayer(shapeLayer)
    }
}

用法:txtFiled.getLine()

但它没有显示出来。 让我知道错过了什么或做错了什么?

1 个答案:

答案 0 :(得分:1)

问题在于贝塞尔曲线的坐标计算。您正在使用textfields frame的原点作为路径。在添加UITextField的路径而不是容器时,应该使用bounds origin来计算路径的坐标。更正了以下代码:

extension UITextField {

    func getLine() {
        let x1 = self.bounds.origin.x
        let y = self.bounds.origin.y + self.frame.size.height
        let start = CGPoint(x: x1, y: y)

        let x2 = self.bounds.origin.x + self.frame.size.width
        let end = CGPoint(x: x2, y: y)

        print("\(start) \(end)")

        let path = UIBezierPath()
        path.move(to: start)
        path.addLine(to: end)

        let shapeLayer = CAShapeLayer()
        shapeLayer.path = path.cgPath
        shapeLayer.strokeColor = UIColor.black.cgColor
        shapeLayer.lineWidth = 5.0
        shapeLayer.fillColor = UIColor.clear.cgColor
        self.layer.addSublayer(shapeLayer)
    }
}

Checkoout apple's doc on view programming guide