2

I'm trying to use a dynamic mask for a text field according to the number of characters entered.

I tried to use VMaskTextField, AKMaskField and now I'm using InputMask (https://github.com/RedMadRobot/input-mask-ios) and I was only able to make one of the masks work. I want to mask as ###.###.###-## or ##.###.###/####-## but I couldn't make to change the mask while the user types. I followed two wiki posts https://github.com/RedMadRobot/input-mask-ios/wiki/Quick-Start and https://github.com/RedMadRobot/input-mask-ios/wiki/2.1-Affine-Masks.

Here my actual code:

 @IBOutlet var btnEntrar: UIButton!
    @IBOutlet var txtCpfCnpj: UITextField!
    @IBOutlet var listener: MaskedTextFieldDelegate!

    override func viewDidLoad() {
        super.viewDidLoad()
        listener.affinityCalculationStrategy = .prefix
        listener.primaryMaskFormat = "[000].[000].[000]-[00]"
        listener.affineFormats = [
            "[00].[000].[000]/[0000]-[00]"
        ]

    }

Here is the main.storyboard:

Main.storyboard

I created the listener as suggested on the wiki posts and it's now working. The field doesn't accept more characters than 11 characters, which corresponds to the first mask ([000].[000].[000]-[00])

Does anyone know how to this dynamic mask in any other way or using some framework?

Thanks

1 Answers1

3

InputMask author here.

MaskedTextFieldDelegate switches between available masks based on its AffinityCalculationStrategy. According to your code, you are using a .prefix strategy, which won't do the trick unless the end user types that dot symbol all by himself.

Unfortunately, the second strategy currently available to you (the .wholeString one) won't help you out neither.

It seems obvious to me that the library currently lacks one more AffinityCalculationStrategy based on the input value length. I'm going to add it over this weekend, so please stay tuned.

UPD. I've made a feature request regarding this functionality.

  • Thanks for your answer. I just saw your feature request. I ended up doing two masks but I will get your new version and test it. Thanks again! – David Palmeira Jun 17 '19 at 13:34
  • @Jeorge Taflanidi: I have an existing project targetting iOS 12. I added pod 'InputMask' in my pod file and did an install. I now see the project in my Pods section. I select the UITextField that I want to mask but I can't see MaskedTextFieldDelegate in the custum class drop down. Any hint ? – Regis St-Gelais Mar 09 '23 at 14:17