Reputation: 3708
I have a textfield, added from storyboard, trying to add line in bottom of textfield using CAShapeLayer and 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)
}
}
Usage : txtFiled.getLine()
But it is not showing. Let me know what missed or anything incorrect doing?
Upvotes: 0
Views: 1711
Reputation: 782
The problem is in your coordinate calculation for the bezier path. You are using textfields frame's origin for your path. You should use bounds origin for calculation your path's coordinate as you are adding the path to UITextField not the container. Corrected code below:
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
Upvotes: 1