Skip to content

2.1 Affine Masks

Egor Taflanidi edited this page Feb 4, 2019 · 4 revisions

You may want to switch between mask formats depending on the input. Say, most of your phone numbers have their primary format like this:

+7 ([000]) [000] [00] [00]

But some of them may have an operator code:

+7 ([000]) [000] [00] [00]#[900]

Such that, when user starts to enter an operator code, the format is switched from the former to the latter.

Input                     Current Mask                        Complete

+7 (123) 456 78           +7 ([000]) [000] [00] [00]          False
+7 (123) 456 78 9         +7 ([000]) [000] [00] [00]          False
+7 (123) 456 78 90        +7 ([000]) [000] [00] [00]          True
+7 (123) 456 78 90#3      +7 ([000]) [000] [00] [00]#[900]    False
+7 (123) 456 78 90#33     +7 ([000]) [000] [00] [00]#[900]    True
+7 (123) 456 78 90#333    +7 ([000]) [000] [00] [00]#[900]    True

Put your additional formats into the affineFormats property:

open class ViewController: UIViewController, MaskedTextFieldDelegateListener {
    @IBOutlet weak var listener: MaskedTextFieldDelegate!
    
    open override func viewDidLoad() {
        super.viewDidLoad()
        listener.affinityCalculationStrategy = .prefix
        listener.affineFormats = [
            "+7 ([000]) [000] [00] [00]#[900]"
        ]
    }    
}

— same works for MaskedTextInputListener and MaskedTextViewDelegate objects.

You may also want to set the affinityCalculationStrategy. AffinityCalculationStrategy.prefix configuration works better when your affine formats have distinctive prefixes, e.g. +1 ( and 8 (, though the default one, .whole, performs better when the entire value is inserted from the clipboard.

Affinity is an integer number, which represents the similarity between the input and the current mask. Thus, the mask with the highest affinity is picked to format the output and to extract the value.

Clone this wiki locally