Custom UITextField for Filtering Input Text
suggest changeThis custom UITextField keeps digits and drops every other character.
On iPhone, .numberPad limits the keyboard to digits. iPad does not provide .numberPad, so the filter below still matters there.
class NumberTextField: UITextField {
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
private func commonInit() {
keyboardType = .numberPad
NotificationCenter.default.addObserver(self, selector: #selector(textDidChange), name: .UITextFieldTextDidChange, object: self)
}
deinit {
NotificationCenter.default.removeObserver(self)
}
@objc private func textDidChange() {
let filtered = filteredText()
if text != filtered {
text = filtered
}
}
private func filteredText() -> String {
let inverseSet = CharacterSet(charactersIn: "0123456789").inverted
let components = (text ?? "").components(separatedBy: inverseSet)
return components.joined(separator: "")
}
}
Use NumberTextField wherever the field should accept only digits. Assign that class in the storyboard’s Identity Inspector, or create it in code.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents