ios - Swift 4 shouldChangeCharactersIn 只显示长度 = 12

标签 ios swift uitextfield

我有 textfieldshouldChangeCharactersIn 代码我使用条形码,系统和我的条形码代码 == 12 个字符。如果条形码小 12 个字符或大必须返回 false 或干净的文本字段,我只想在我的字符串中显示 12 个字符。我的代码在下面。当我使用条形码时,如果我的条形码 12 个字符工作正常,但如果我读取 12 个字符低,请不要清除文本字段,

How can I fix it ?

我的代码在下面。

 func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {

        let length = (Mytext.text?.characters.count)! - range.length + string.characters.count
        if length == 13 {

            print("Mytext=\(Mytext.text!)")
            Mytext.text = ""

            return true

        }else {


            return true
        }


    }

读取12个字符条码时输出显示成功! 当阅读低 12 个字符时不要清除 Mytext 字段,当我再次阅读时添加 +

最佳答案

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {

    if (string != "" && textField.text?.count == 12) {

        print("Mytext = \(textField.text!)")
        textField.text = ""
        return false
    }

    return true
}

关于ios - Swift 4 shouldChangeCharactersIn 只显示长度 = 12,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47642393/

相关文章:

ios - 方向改变后在 Unwind Segue 上崩溃

xcode - Swift 2.0 Xcode 7.1 图像选择器前置摄像头图像在选择时旋转

ios - NSKeyedUnarchiver.unarchiveObject 不工作

iOS)在 UITableView 的单元格中隐藏键盘

ios - 自定义输入 View 执行。除非打开默认键盘,否则自定义 inputView 不会出现

ios - 文本字段中的对齐不起作用

ios - 与 iOS 6 一起使用的 AdMob 使应用程序崩溃(无法识别的选择器)

ios - 从 TableView 中检索值

ios - 将 MapKit 地点与 Facebook 地点相匹配

swift - 如何在 firebase 观察者路径中使用通配符?