UITextField 下划线宽度问题

UITextField underline width issue

我有一个 UITextFieldUIButton 放置在垂直 UIStackView 中。我以编程方式添加了 UIView 作为 UITextField 的下划线。

编译代码的时候出现了问题。该行比文本字段长。我已经打印了上面所有对象的宽度,它显示 335

我在 viewWillAppear 中称此为 function 并且该行更长。如果我在 viewDidAppear 中调用它,该行是 UITextField 的确切宽度,但您可以看到按钮和文本字段在更新视图之前非常短暂地闪烁。我究竟做错了什么?

override func viewDidLoad()  {
    super.viewDidLoad()
    observeKeyboardNotifications()
    textFieldDelegate()
    setupRegisterButton()

}

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
     setupTextFields()
}

func setupTextFields() {

    emailTextField.leftViewMode = .always
    let emailIconView = UIImageView()
    emailIconView.frame = CGRect(x: 0, y: 0, width: 23, height: 17)
    emailIconView.image = UIImage(named: "icon_email")
    let bgIconView = UIView(frame: CGRect(x: 0, y: 0, width: 28, height: 17))
    bgIconView.addSubview(emailIconView)
    emailTextField.leftView = bgIconView

    emailTextField.tintColor = .white
    emailTextField.textColor = .white
    emailTextField.backgroundColor = .red
    emailTextField.borderStyle = .roundedRect
    let bottomLineEmail = CALayer()
    bottomLineEmail.frame = CGRect(x: 0, y: 29, width: emailTextField.frame.width, height: 1)
    print("Email width", emailTextField.frame.width)
    print("button width", retrievePasswordButton.frame.width)
    print("line width", bottomLineEmail.frame.width)
    bottomLineEmail.backgroundColor = UIColor.white.cgColor
    emailTextField.layer.addSublayer(bottomLineEmail)
    //emailTextField.backgroundColor = .clear
    emailTextField.attributedPlaceholder = NSAttributedString(string     : emailTextField.placeholder!,
                                                              attributes : [NSAttributedStringKey.foregroundColor: Colors.authTextFieldPlaceholderColor])
    retrievePasswordButton.isEnabled = false
    handleTextFields()
}

我亲自查过 它适用于 ViewWillLayoutSubviews

override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews();
    self.setupTextFields()
}

和 viewDidAppear

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)
    self.setupTextFields();
}