用户键入时的 Swift 格式文本字段 [英] Swift format text field when user is typing

查看:32
本文介绍了用户键入时的 Swift 格式文本字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试格式化到期字段,以便将文本格式化如下:MM/YY当用户输入时,我可以让文本字段添加额外的字符,但是当我删除数字时,代码将不允许您在再次添加/"之前传递两个字符.有什么方法可以识别用户何时删除并绕过文本字段检查?

I'm trying to format an expiry field so that it formats the text as follows: MM / YY I can get the textfield to add in the extra characters when the user is typing however when I come to delete the numbers the code will not allow you to go passed two characters before adding in the " / " again. Is there a way I can recognise when the user is deleting and bypass the text field check?

ExpiryOutlet.addTarget(self, action: #selector(ExpiryDidChange(_:)), for: .editingChanged)

func ExpiryDidChange(_ textField: UITextField) {
    if textField == ExpiryOutlet {

        if textField.text != "" && textField.text?.characters.count == 2 {
            textField.text = "\(textField.text!) / "
        }

    }
}

谢谢

推荐答案

有什么方法可以识别用户何时删除并绕过文本字段检查?

Is there a way I can recognise when the user is deleting and bypass the text field check?

问题在于您实施了错误的方法.实现委托方法text Field(_: should Change Characters In: replacement String: ).这允许您区分哪里文本正在改变(第二个参数是范围),以及什么新文本——在退格的情况下,replacementString 将为空.

The problem is that you've implemented the wrong method. Implement the delegate method text​Field(_:​should​Change​Characters​In:​replacement​String:​). This allows you distinguish where the text is changing (the second parameter is the range), and what the new text is — in the case of the backspace, replacementString will be empty.

这篇关于用户键入时的 Swift 格式文本字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆