我有一个自定义文本字段,在其中添加了一个错误标签。我想调整此自定义文本字段的大小,以使其扩展为带有多行错误标签,并且不会与其下方的其他字段重叠。在IB中,我已正确固定视图,所以这不是问题。
如何解决?
class LoginViewController: UIViewController {
@IBOutlet weak var emailTextField: CustomTextField!
@IBOutlet weak var passwordTextField: CustomTextField!
override func viewDidLoad() {
super.viewDidLoad()
emailTextField.setError("Multiple line error. Multiple line error. Multiple line error. Multiple line error.")
}
}
class CustomTextField: UITextField {
var bottomBorder = UIView()
var errorLabel = UILabel()
override init(frame: CGRect) {
super.init(frame: frame)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func awakeFromNib() {
super.awakeFromNib()
self.initialize()
// Setup Bottom-Border
// ....
errorLabel.translatesAutoresizingMaskIntoConstraints = false
self.addSubview(errorLabel)
errorLabel.topAnchor.constraint(equalTo: self.bottomBorder.bottomAnchor, constant: 4).isActive = true
errorLabel.leadingAnchor.constraint(equalTo: self.leadingAnchor).isActive = true
errorLabel.trailingAnchor.constraint(equalTo: self.trailingAnchor).isActive = true
errorLabel.numberOfLines = 0
errorLabel.lineBreakMode = .byWordWrapping
errorLabel.sizeToFit()
}
func initialize() {
self.text = ""
self.clearError()
// ...
}
func setError(error: String) {
self.errorLabel.text = error
self.errorLabel.isHidden = false
self.setNeedsLayout()
self.layoutIfNeeded()
}
func clearError() {
self.errorLabel.text = ""
self.errorLabel.isHidden = true
}
}
[UITextField
只有1行,您需要使用UITextView
或更好的方法