UITextField subclass replace(_:withText:) does not get called. Text formatter conception.

Hi!

Being an iOS developer I always wonder why text input controls on Mac have the ability to set text formatters while iOS controls have not.


The basic idea of text formatter is to handle a request for text change and apply it in very own way (like insert other text instead of proposing or deny it at all).

We also have an UITextInput protocol who has the method looks right.

I thought that the right way to format user input is to write an UITextField subclass and override UITextInput required method:

public override func replace(_ range: UITextRange, withText text: String)

But this method got never called.


I know two workarounds: 1. Set delegate and handle `shouldChangeText(_:replacementText)` and subscribing to control's `valueChanged`.

Both cases are conceptionally incorrect in my opinion and here is why:

1. Delegate method should only return `true` or `false`. Changing text right in this methods looks like a horrible side-effect.

Just imagine that we really only want to know whether a text changing os possible. Changing the text is not appropriate at the moment of checking.

2. Handling 'textDidChange' notification is better, but conceptionally it's like an attempt to quickly heal a wound instead of preventing it. Also, we have no information what part of the text changed, only speculate about. Did user paste the text? Did he change just the word in the middle or paste the whole text which was identical to previous text except the word in the middle?


So my questions are:

1. Is there any way to handle and transform user input before it goes to control?

2. Do you have an idea why overriding `replace(_ range: UITextRange, withText text: String)` does not work?

Apple's documentation says:


The

UITextField
class does not provide built-in support for formatting its string using an
Formatter
object, but you can use the text field’s delegate to format the content yourself. To do so, use the text field’s delegate methods to validate text and to format it appropriately. For example, use the
textField(_:shouldChangeCharactersIn:replacementString:)
method to validate and format text while the user is typing.


While I still believe that this way is conceptionally wrong I have to format text user input using a delegate.

And I probably should write a bug report about the second question after a little research.

UITextField subclass replace(_:withText:) does not get called. Text formatter conception.
 
 
Q