简体   繁体   English

如何快速动态屏蔽文本字段

[英]How to dynamically mask a text field with swift

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. 我尝试使用VMaskTextField,AKMaskField,现在使用InputMask( https://github.com/RedMadRobot/input-mask-ios ),但我只能使其中一个面具起作用。 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 . 我关注了两个Wiki帖子https://github.com/RedMadRobot/input-mask-ios/wiki/Quick-Starthttps://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:

Main.storyboard

I created the listener as suggested on the wiki posts and it's now working. 我按照Wiki帖子上的建议创建了侦听器,现在可以正常工作了。 The field doesn't accept more characters than 11 characters, which corresponds to the first mask ([000].[000].[000]-[00]) 该字段接受的字符数不能超过11个字符,这对应于第一个掩码([000]。[000]。[000]-[00])

Does anyone know how to this dynamic mask in any other way or using some framework? 有谁知道如何通过其他方式或使用某些框架来使用此动态掩码?

Thanks 谢谢

InputMask author here. InputMask作者在这里。

MaskedTextFieldDelegate switches between available masks based on its AffinityCalculationStrategy . MaskedTextFieldDelegate根据其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. 根据您的代码,您使用的是.prefix策略,除非最终用户自己键入全部加点符号,否则不会成功。

Unfortunately, the second strategy currently available to you (the .wholeString one) won't help you out neither. 不幸的是,您现在可以使用的第二种策略( .wholeString策略)也不会帮助您。

It seems obvious to me that the library currently lacks one more AffinityCalculationStrategy based on the input value length. 对我来说似乎很明显,该库当前缺少基于输入值长度的AffinityCalculationStrategy I'm going to add it over this weekend, so please stay tuned. 我将在这个周末添加它,所以请继续关注。

UPD. UPD。 I've made a feature request regarding this functionality. 我已就此功能提出了功能要求

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM