Im trying to build a custom UITextField that shows a validation error inline below the textfield akin to material design. Im adding a UILabel lazily and constraining to the textfield when i present the error
private lazy var errorLabel: UILabel = {
let label = UILabel()
label.font = UIFont.systemFont(ofSize: 14, weight: .bold)
label.textColor = errorColor
label.numberOfLines = 0
label.isHidden = true
return label
}()
open override func didMoveToSuperview() {
super.didMoveToSuperview()
// Make sure that errorLabel is added once to the superview, not to the text field itself
if let superview = superview, errorLabel.superview == nil {
superview.addSubview(errorLabel)
configureErrorLabelConstraints()
}
}
private func configureErrorLabelConstraints() {
errorLabel.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
errorLabel.topAnchor.constraint(equalTo: self.bottomAnchor, constant: 5),
errorLabel.leadingAnchor.constraint(equalTo: self.leadingAnchor),
errorLabel.trailingAnchor.constraint(equalTo: self.trailingAnchor)
])
public func showInlineValidationError(message: String) {
errorLabel.textColor = errorColor
layer.borderColor = errorColor.cgColor
errorLabel.text = message
errorLabel.isHidden = false
}
public func hideInlineValidationError() {
layer.borderColor = borderColor.cgColor
errorLabel.isHidden = true
}
}
This all works great. My issue is, say i have a UIImage constrained 12 points below the custom textfield, when the label is presented it does not move the image down by the label height, and rather reduces the space between the two. What i want is if the label is displayed, the constraint between the textfield and image to be increased by how much additional height the label takes up. How can i go about this? AI has not been helpful at all in what i might be able to do here.
Im open to a 3rd party library if its basic enough. I just need a basic UITextfield with rounded corners and the error label below that can support my height change requirements
2
Answers
This is similar to what sonle suggested. I ended up moving this to a UIView containing a stackview and hide/show the label. if i have a height constraint it must be set to greater than or equal to so the view is allow to grow with the stackview.
Update: According to your comment I assume this is what you’re looking for.
ValidationTextField
, that contains three subviews like below.EmailTextField
.And this is what
EmailTextField
could look like:I think the better approach for this scenario is to add a container StackView that contains all
textField
,errorLabel
andimageView
vertically.Then you can simply toggle the
errorLabel
regardless of Label’s height and the constraints between TextField and ImageView.Output: