【发布时间】:2019-01-17 11:53:02
【问题描述】:
我有一个UITextField 和UIButton 放置在一个垂直的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()
}
【问题讨论】:
-
不要在
viewWillAppear中添加views/layers,该方法可以被多次调用。不,viewWillAppear中的帧不正确。使用viewDidLayoutSubviews。此外,使用更简单的UIView和自动布局会更简单。 -
@Sulthan 在
viewDidLayoutSubviews中调用它并没有按预期工作。下划线的宽度仍然比文本字段本身长。 -
@Dani 不要添加层,为什么不在堆栈视图中添加该大小和约束的视图。
-
@JarvisTheAvenger 是的,这就是我最终所做的。似乎轻松了许多。谢谢
-
@Dani 很高兴听到这个消息。快乐编码。
标签: swift uiview uitextfield viewdidappear