2

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.

jjatie
  • 5,152
  • 5
  • 34
  • 56
  • `UITextFieldDelegate` has a method called `shouldChangeCharactersIn....` Not `UITextField`, though. https://developer.apple.com/reference/uikit/uitextfielddelegate/1619599-textfield – danh Jan 19 '17 at 03:49
  • 1
    @danh They both have the method, with slightly different naming – jjatie Jan 19 '17 at 12:08
  • Can you provide an Apple doc link? – danh Jan 19 '17 at 13:25
  • @danh https://developer.apple.com/reference/uikit/uitextinput/1614495-shouldchangetext – jjatie Jan 19 '17 at 13:26
  • I see. The discussion says it's called on the delegate. Not sure what object that is. – danh Jan 19 '17 at 13:43
  • I interpreted the docs as this being the method that calls the delegate. It's a protocol that all the text input views adopt (UITextField, UITextView, NSTextView, etc.) – jjatie Jan 19 '17 at 13:45
  • I agree this is not working as designed. Perhaps you could submit at bug at https://bugreport.apple.com/ – Alexander Smith Dec 04 '17 at 04:47

0 Answers0