Ali Alebrahim Ali Alebrahim - 1 year ago 412
Swift Question

Adding Bottom Line Border To A TextView - iOS

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

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

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.masksToBounds = true

The TextView has a dynamic height.

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download