UITextField Subclass not calling shouldChangeText(in range:replacementText:)

817 Views Asked by At

I have a subclass of UITextField that works in all respects except that the overridden method shouldChangeText(in range:replacementText:) is not being called. I am trying to make a field that permits the user to enter only valid decimal numbers, and got that working in the equivalent delegate method, but since I will be using this in many places I want to just subclass it once.

My entire class is

class FWNumberField: FWTextField {

    override func shouldChangeText(in range: UITextRange, replacementText text: String) -> Bool {
        if text == ".", self.text == nil || self.text!.isEmpty || self.text!.contains(".") {
            return false
        } else {
            return true
        }    
    }

    override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
        if action == #selector(UIResponderStandardEditActions.paste(_:)) { return false }

        return super.canPerformAction(action, withSender: sender)
    }
}

Where FWTextField is a subclass of UITextField that adds a simple inputAccessoryView that has a "Done" button, and the keyboard is restricted to a decimal keyboard in my Storyboard.

My storyboard and IBOutlet both have their types set to FWNumberField. Any thoughts on why the method isn't being called? The docs say it should be.

0

There are 0 best solutions below