Swift UITextField十进制字段类型 - 无粘贴,仅1个小数点和长度限制

时间:2016-06-01 07:53:58

标签: ios swift validation uitextfield

我正在尝试对一个只接受十进制值的文本字段进行错误检查。这意味着无法粘贴文本字段,用户只能输入1个小数点,我的个人喜好我希望小数点后的长度限制为2个字符。

我有当前的代码,只是限制了粘贴:

//Does not allow pasting into text field
    //https://stackoverflow.com/questions/26919854/how-can-i-declare-that-a-text-field-can-only-contain-an-integer
    func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {

        let invalidCharacters = NSCharacterSet(charactersInString: "0123456789.").invertedSet
        return string.rangeOfCharacterFromSet(invalidCharacters, options: [], range: string.startIndex ..< string.endIndex) == nil

    }

它有效,但我也想要其他功能。我该如何实现这些?

2 个答案:

答案 0 :(得分:0)

要检查它是否有小数点并限制2位小数,您可以这样使用: -

 let str = "456.23" // Your Label Value
 let nsStr = NSString(string: str) // Conver label value to NSString
 let strSplit = str.characters.split(".") // split label before decimal point and after decimal point
 if str.containsString(".") {
      //Contains Decimal value
      if String(strSplit.last!).characters.count <= 2 {
         // Contains 2 or 1 decimal values
      } else {
         // More than 2 decimal values
      }
 } else {
     //Do not contains Decimal value
 }

答案 1 :(得分:0)

你可以做点什么,

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

    var dotLocation = Int()



    let nonNumberSet = NSMutableCharacterSet() //create an empty mutable set
    nonNumberSet.formUnionWithCharacterSet(NSCharacterSet.URLQueryAllowedCharacterSet())
    nonNumberSet.addCharactersInString("0123456789.")


    //allow backspace
    if range.length == 0 && string.characters.count == 0
    {
        return true
    }


    if string == "."
    {
        if range.location == 0{
            return false
        }
        if dotLocation == 0 {

            dotLocation == range.location
            return true
        }
        else{


            return false
        }

    }


    if range.location == dotLocation && string.characters.count == 0{

        dotLocation = 0
    }

    var newStr = (textField.text! as NSString).stringByReplacingCharactersInRange(range, withString: string)
    newStr = (newStr.componentsSeparatedByCharactersInSet(nonNumberSet) as NSArray).componentsJoinedByString("")
    textField.text = newStr
    return false

}

希望这会有所帮助:)