Reputation: 1258
I've a custom text field in which I'm adding an error label below text field. 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. In IB I've pinned view properly so that is not an issue.
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
}
}
Upvotes: 0
Views: 294
Reputation: 100503
UITextField
is only 1 line you need to use UITextView
or better do
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
Upvotes: 2