ios UITextField -以编程方式底线

7fhtutme  于 2023-05-02  发布在  iOS
关注(0)|答案(2)|浏览(153)

我试图为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
}()
vatpfxk5

vatpfxk51#

试试下面的代码。

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
    }
j2cgzkjk

j2cgzkjk2#

在执行下面的代码时,textField.frame.width似乎为零:

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

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

相关问题