Rules will tell the formatter which characters from the mask are supposed to be replaced by what (letter, number, etc)
In our “expiration date” mask example (##/##), we have two different characters, # and /. We want to replace #, thus we will create a rule for that character.
In order to tell which input is valid for that specific character, we use the validation parameter. This parameter receives a Character and returns a Bool:
Columbina’s Masked Formatter
A fully customizable formatter used to create masks for texts.
Quick start
1. Import the module
2. Define a mask
For instance, an “expiration date” mask, commonly used for credit card forms, can be defined as such:
3. Define the rules
Using the same example for an “expiration date” mask, this is how our rule would look like:
4. Initiate a MaskedFormatter
5. Apply formatter
Tips
Create your own formatters
For instance, by inheriting MaskedFormatter:
Apply to UITextField
Mask a UITextField in “realtime” by listening to changes in the textfield:
Apply to SwiftUI’s TextField
Mask a TextField in “realtime” through
onChange
:More details
Rule
Rules will tell the formatter which characters from the mask are supposed to be replaced by what (letter, number, etc) In our “expiration date” mask example (
##/##
), we have two different characters,#
and/
. We want to replace#
, thus we will create a rule for that character.In order to tell which input is valid for that specific character, we use the validation parameter. This parameter receives a Character and returns a Bool:
In our example, we want the
#
character to be replaced by a number, so we can checkchar
and see if it is a number:Now we can use this rule in one or more MaskedFormatters: