[英]Auto resize custom text field for multiple lines label
I've a custom text field in which I'm adding an error label below text field.我有一个自定义文本字段,其中我在文本字段下方添加了错误 label。 I want to resize this custom text field so that it expands with multiple line error label and doesn't overlap with other fields below it.
我想调整这个自定义文本字段的大小,使其扩展为多行错误 label 并且不与下面的其他字段重叠。 In IB I've pinned view properly so that is not an issue.
在 IB 中,我已正确固定视图,因此这不是问题。
How to fix it?如何解决?
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
is only 1 line you need to use UITextView
or better do UITextField
是只有 1 行你需要使用UITextView
或更好
class CustomView: UIView {
let textfield = UITextField()
let bottomBorder = UIView()
let errorLabel = UILabel()
.....
}
So the view will expand according to sum of textfield height, border height and label text height因此视图将根据文本字段高度、边框高度和 label 文本高度之和展开
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.