Add bottom line to view in SwiftUI / Swift / Objective-C / Xamarin

前端 未结 22 2355
自闭症患者
自闭症患者 2020-11-27 09:19

I would like to keep the border at the bottom part only in UITextField. But I don\'t know how we can keep it on the bottom side.

Can you please advise m

22条回答
  •  佛祖请我去吃肉
    2020-11-27 09:48

    You can create this extension outside class and replace width with whatever borderWidth you want.

    Swift 4

    extension UITextField
    {
        func setBottomBorder(withColor color: UIColor)
        {
            self.borderStyle = UITextBorderStyle.none
            self.backgroundColor = UIColor.clear
            let width: CGFloat = 1.0
    
            let borderLine = UIView(frame: CGRect(x: 0, y: self.frame.height - width, width: self.frame.width, height: width))
            borderLine.backgroundColor = color
            self.addSubview(borderLine)
        }
    }
    

    Original

    extension UITextField
    {
        func setBottomBorder(borderColor: UIColor)
        {
            self.borderStyle = UITextBorderStyle.None
            self.backgroundColor = UIColor.clearColor()
            let width = 1.0
    
            let borderLine = UIView(frame: CGRectMake(0, self.frame.height - width, self.frame.width, width))
            borderLine.backgroundColor = borderColor
            self.addSubview(borderLine)
        }
    }
    

    and then add this to your viewDidLoad replacing yourTextField with your UITextField variable and with any color you want in the border

    yourTextField.setBottomBorder(UIColor.blackColor())
    

    This basically adds a view with that color at the bottom of the text field.

提交回复
热议问题