Ali Alebrahim Ali Alebrahim - 4 months ago 150
Swift Question

Adding Bottom Line Border To A TextView - iOS

what is the best way to add a bottom line border to a

TextView
?
i have tried this but it seems it doesn't work. It is affected by the scrolling ability of the
textview
and the line is being drawn in the middle of the
TextView


func addBottomBorderWithColor(color: UIColor, width: CGFloat) {
let border = CALayer()
border.backgroundColor = color.CGColor
border.frame = CGRectMake(0, self.frame.size.height - width, self.frame.size.width, width)
self.layer.addSublayer(border)
self.layer.masksToBounds = true
}


Edit:
The TextView has a dynamic height.

Answer

Does self in your code mean TextView?

If so, when you add border as a sublayer of the TextView, the border will move up and down when the user scrolls the text of TextView.

Try to add border as a sublayer of TextView's super view rather than TextView itself.

Here is the code (Note that I change border from CALayer to UIView):

func addBottomBorderWithColor(color: UIColor, width: CGFloat) {
     let border = UIView()
     border.frame = CGRectMake(self.frame.origin.x, self.frame.origin.y+self.frame.height-width, textView.frame.width, width)
     border.backgroundColor = color
     self.superview!.insertSubview(border, aboveSubview: textView)
 }

Here is the capture:

enter image description here

PS. I suggest you to change the second paramter name from width to height since width is ambiguous in this context.