如何使用 swift 动态屏蔽文本字段

How to dynamically mask a text field with swift

我正在尝试根据输入的字符数为文本字段使用动态掩码。

我尝试使用 VMaskTextField、AKMaskField,现在我正在使用 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

这里是我的实际代码:

 @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]"
        ]

    }

这里是 main.storyboard:

我按照 wiki 帖子中的建议创建了侦听器,现在可以正常使用了。该字段不接受超过 11 个字符的字符,对应于第一个掩码 ([000].[000].[000]-[00])

有谁知道如何以任何其他方式或使用某些框架来使用此动态掩码?

谢谢

InputMask作者在这里

MaskedTextFieldDelegate 根据其 AffinityCalculationStrategy 在可用掩码之间切换。根据您的代码,您使用的是 .prefix 策略,除非最终用户自己键入该点符号,否则该策略不会奏效。

不幸的是,您当前可用的第二种策略(.wholeString 一种)也不会帮助您。

在我看来,根据输入值的长度,库目前还缺少一个 AffinityCalculationStrategy。这个周末我会补上的,敬请期待

更新。关于这个功能,我做了一个 feature request