在Swift3 iOS中的UITextField中只允许使用数字和点字符

时间:2018-05-17 08:08:29

标签: ios swift3 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 %

我在Code下面使用它来实现这个目标:

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

}

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

1 个答案:

答案 0 :(得分:0)

请在输入

时找到更新的代码,以便将百分比添加到最后一个数字
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

    }