首页 > 解决方案 > Swift3 iOS 中的 UITextField 中只允许使用数字和点字符

问题描述

我正在对我的 UITextField 进行验证。它应该只接受数字和。特点。基本上用户可以输入任何十进制数字,例如:

1.0
1.23
1.45
12.47

我还必须在文本字段中编辑时添加 % 符号,如下所示:

When User enter 1, textfield should update 1 %

When User enter 1.2, textfield should update 1.2 %

When User enter 18.345, textfield should update 18.345 %

我正在使用下面的代码来实现这一点:

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

    if string.characters.count == 0 {
        return true
    }
    do {
        if textField == self.questionTextFeild {

            let nString = textField.text as NSString?
            let newString = nString?.replacingCharacters(in: range, with: string)
            let expression = "^([0-9]+)?(\\.([0-9]{1,8})?)?$"
            let regex = try NSRegularExpression(pattern: expression, options: .caseInsensitive)
            let numberOfMatches = regex.numberOfMatches(in: newString! as String, options: [], range: NSRange(location: 0, length: (newString?.characters.count)!))

            //textField.text = textField.text!
            if numberOfMatches == 0 {
                return false
            }
        }
    }
    catch let error {
    }
    return true

}

使用它我可以输入数字和点字符。我的问题是如何添加 % 符号?请给我建议。

标签: iosswift3uitextfield

解决方案


请找到更新的代码,以便在键入时将百分比添加到数字的最后一个

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

        if string.count == 0 {
            return true
        }
        do {
            if textField == textField {

                let nString = textField.text as NSString?
                let newString = nString?.replacingCharacters(in: range, with: string)
                if var textString = textField.text {
                    let unitString = " %"
                    if textString.contains(unitString) {
                        textString = textString.replacingOccurrences(of: unitString, with: "")
                        textString += string + unitString
                        textField.text = textString
                    } else {
                        textField.text = string + unitString
                    }
                }
                let expression = "^([0-9]+)?(\\.([0-9]{1,8})?)?$"
                let regex = try NSRegularExpression(pattern: expression, options: .caseInsensitive)
                let numberOfMatches = regex.numberOfMatches(in: newString! as String, options: [], range: NSRange(location: 0, length: (newString?.count)!))

                //textField.text = textField.text!
                if numberOfMatches == 0 {
                    return false
                }
            }
        }
        catch let error {
            print(error.localizedDescription)
        }
        return true

    }

推荐阅读