UITextField - 以编程方式的底线

UITextField - bottom line programmatically

我正在尝试为 UITextField 添加底线 ... 我做错了什么?

    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
}()

执行以下代码行时 textField.frame.width 似乎为零:

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

因此,您应该在通过约束或框架大小为 emialTextField 设置大小后,将 bottomline 图层添加到文本字段。

试试下面的代码。

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
    }