Sebastian
Sebastian

Reputation: 73

UITextField - bottom line programmatically

I am trying to add a bottom line to UITextField ... what am I doing wrong?

    let emialTextField: UITextField = {
    let textField = UITextField()
    textField.layer.cornerRadius = 5
    textField.borderStyle = .none
    textField.placeholder = "emial adress"
    let bottomline = CALayer()
    bottomline.frame = CGRect(x: 0, y: textField.frame.height - 2, width: textField.frame.width, height: 2)
    bottomline.backgroundColor = UIColor.init(red: 0/255, green: 0/255, blue: 0/255, alpha: 1).cgColor
    textField.layer.addSublayer(bottomline)

    return textField
}()

Upvotes: 1

Views: 178

Answers (2)

Tushar Sharma
Tushar Sharma

Reputation: 2882

Try below code.

override func viewDidLoad() {
        super.viewDidLoad()
       
        let emialTextField: UITextField = {
            let textField = UITextField(frame: CGRect(x: 100, y: 90, width: 100, height: 30))
            textField.borderStyle = .none
            textField.placeholder = "emial adress"
            let bottomline = CALayer()
            bottomline.frame = CGRect(x: 0, y: textField.frame.height + 1, width: textField.frame.width, height: 2)
            bottomline.backgroundColor = UIColor.init(red: 3/255, green: 4/255, blue: 5/255, alpha: 1).cgColor
            textField.layer.addSublayer(bottomline)
            return textField
        }()
        
      
        
        view.addSubview(emialTextField)
        emialTextField.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 100).isActive = true
        emialTextField.topAnchor.constraint(equalTo: view.topAnchor, constant: 90).isActive = true
        emialTextField.heightAnchor.constraint(equalToConstant: 30).isActive = true
        emialTextField.widthAnchor.constraint(equalToConstant: 100).isActive = true
    }

Upvotes: 1

Mohammad Eslami
Mohammad Eslami

Reputation: 544

It seems textField.frame.width is zero when executing below line of your code:

bottomline.frame = CGRect(x: 0, y: textField.frame.height - 2, width: textField.frame.width, height: 2)

So you should add bottomline layer to your text field after size set for emialTextField via constraint or frame size.

Upvotes: 1

Related Questions