UITextField下划线宽度问题

时间:2019-01-17 11:53:02

标签: swift uiview uitextfield viewdidappear

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

当我编译代码时,问题就来了。该行比文本字段长。我已经在上面打印了所有对象的宽度,上面写着335

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

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

1 个答案:

答案 0 :(得分:0)

我亲自检查过 它可以在ViewWillLayoutSubviews

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

和viewDidAppear

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

proof