'Bottom Border for UITextField in Swift

I found this question with a solution to my problem but it still has some misbehavior when I'm using it. How to only show bottom border of UITextField in Swift

In my Project it seems like the bottom border doesn't know the correct width of my UITextField and is longer than my UITextField. The UITextField has constraints to the SaveArea on the left and right and a constraint to the text above. I would say that the width is defined by the constraints at run time so that the code in the extension should be able to get the correct width. But the way my code is getting the width seems to be wrong. Can someone help me?

Code example

Thanks in advance :)



Solution 1:[1]

I know you found a workaround but just thought I might add a fix for this if you still were considering using this.

So it seems that your set up was fine but it works a little bit differently on different device sizes.

self.frame.size.width in the extension is not always returning back the correct width of the UITextField in some devices and on orientation changes.

So to get this to work, here are the small changes I made:

extension UITextField
{
    func addBottomBorder() {
        let bottomLine = CALayer()
        
        // The border should be inside the text field
        // so I changed frame.size.height + 5 to
        // frame.size.height - 1
        bottomLine.frame = CGRect(x: 0,
                                  y: frame.size.height-1,
                                  width: frame.size.width,
                                  height: 1)
        
        bottomLine.backgroundColor = UIColor.black.cgColor
        
        borderStyle = .none
        
        layer.addSublayer(bottomLine)
        
        // Add this so the layer does not go beyond the
        // bounds of the text field
        layer.masksToBounds = true
    }
}

After this, the result should be as you hope:

Bottom Border for UITextField in Swift using CALayer AutoLayout

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Shawn Frank