如何将文本字段限制为仅有效的小数?
Posted
技术标签:
【中文标题】如何将文本字段限制为仅有效的小数?【英文标题】:How to restrict a text field to only valid decimals? 【发布时间】:2016-03-20 05:23:38 【问题描述】:在我的应用程序中,用户必须在文本字段中输入小数点。但是,我不知道如何将文本字段限制为仅有效的小数。我尝试了一个示例here,但文本字段仍然允许我输入多个小数点,允许我在文本字段的开头放置一个小数点,并且不允许我删除字符。 谢谢!
【问题讨论】:
检查这个问题:***.com/questions/12944789/… ***.com/questions/10734959/… 或 ***.com/questions/20122455/… 【参考方案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 个逗号或 1 个点 "^([0-9]+)?((\\,|\\.)([0-9]+)?)?$" 【参考方案2】:在您在问题中提供的链接中,代码仅检查一位小数。您必须按如下方式修改您的代码。我引用了您提供的链接中的代码
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
希望对你有帮助
【讨论】:
请注意,此代码不适用于点不是小数分隔符的地区的用户。他们将无法输入非整数值【参考方案3】:这是我已经尝试过并为我工作的方法。
// 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
【讨论】:
以上是关于如何将文本字段限制为仅有效的小数?的主要内容,如果未能解决你的问题,请参考以下文章