簡體   English   中英

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
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM