0

I created a custom text field, a class that extends a UITextField, how can I know if that UITextField has a value, I already tried the shouldChangeCharactersIn but nothing happened.

This is my code for my custom UITextField Class

@IBDesignable class CustomTextField: UITextField {
    override init(frame: CGRect) {
        super.init(frame: frame)
        loadContent()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        loadContent()
    }
    ...
}

I want to print "the textfield is blank" if the UITextField is blank or if the user removed the value in it, and "the textfield has content" if there's a value in it or if the user add a value in it.

1 Answer 1

1

You just need to add a target to your text field for UIControl.Event .editingChanged

override func willMove(toSuperview newSuperview: UIView?) {
    addTarget(self, action: #selector(editingChanged), for: .editingChanged)
}

And use UIKeyInput method hasText to check if your field is empty or not:

@objc func editingChanged(_ textField: UITextField) {
    print("the textfield " + (hasText ? "has content" : "is blank"))
}
Sign up to request clarification or add additional context in comments.

3 Comments

I tried adding the addTarget(self, action: #selector(editingChanged), for: .editingChanged) inside override init(frame: CGRect) but it doesn't print anything whenever I add or removed the text in the textfield
I would override willMoveToSuperview instead of overriding its init method
willMove(toSuperview newSuperview: UIView?) worked for me

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.