如何将文本字段限制为仅有效的小数?

时间:2016-03-20 05:23:38

标签: ios swift validation uitextfield

在我的应用中,用户必须在文本字段中输入小数。但是,我不知道如何将文本字段限制为仅有效的小数。我尝试了一个示例here,但文本字段仍然允许我输入多个小数点,让我在文本字段的开头添加一个小数点,它不允许我删除字符。 如何将文本字段限制为仅有效小数?谢谢!

3 个答案:

答案 0 :(得分:1)

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

let textFieldString = textField.text! as NSString;

var newString = textFieldString.stringByReplacingCharactersInRange(range, withString:string)

let floatRegEx = "^([0-9]+)?(\\.([0-9]+)?)?$"

let floatExPredicate = NSPredicate(format:"SELF MATCHES %@", floatRegEx)

return floatExPredicate.evaluateWithObject(newString)


}

答案 1 :(得分:0)

在您在问题中提供的链接中,代码仅检查一个小数位。您必须按如下方式修改代码。我引用了您提供的链接中的代码

import UIKit

class ViewController: UIViewController, UITextFieldDelegate {

    @IBOutlet weak var textField: UITextField!

    override func viewDidLoad() {
        super.viewDidLoad()
        self.textField.delegate = self
    }

    //Textfield delegates
    func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool { // return false to not change text
        // max 2 fractional digits allowed
        let newText = (textField.text! as NSString).stringByReplacingCharactersInRange(range, withString: string)
        let regex = try! NSRegularExpression(pattern: "\\..{3,}", options: [])
        let matches = regex.matchesInString(newText, options:[], range:NSMakeRange(0, newText.characters.count))
        guard matches.count == 0 else { return false }

        switch string {
        case "0","1","2","3","4","5","6","7","8","9":
            return true
        case ".":
            let array = textField.text?.characters.map { String($0) }
            var decimalCount = 0
            for character in array! {
                if character == "." {
                    decimalCount++
                }
            }
            if decimalCount > 0 {
                return false
            } else {
                return true
            }
        default:
            let array = string.characters.map { String($0) }
            if array.count == 0 {
                return true
            }
            return false
        }
    }
}

希望这有帮助

答案 2 :(得分:0)

这是我尝试过并为我工作的内容。

// TextField Delegate
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool
{
    if string.isEmpty { return true }
    let currentLocale = NSLocale.currentLocale()
    let decimalSeparator = currentLocale.objectForKey(NSLocaleDecimalSeparator) as! String
    let existingTextHasDecimalSeparator = textField.text?.rangeOfString(decimalSeparator)
    let replacementStringHasDecimalSeparator = string.rangeOfString(decimalSeparator)
    let allowedCharactersSet = NSCharacterSet(charactersInString: decimalSeparator + "0123456789")
    let allowedCharacters = string.rangeOfCharacterFromSet(allowedCharactersSet)

    if existingTextHasDecimalSeparator != nil && replacementStringHasDecimalSeparator != nil || allowedCharacters == nil
    {
        return false
    }
    else
    {
        return true
    }
}