将 UITextField 限制为一位小数点 Swift [英] Limit UITextField to one decimal point Swift
问题描述
如何使用 Swift 将 UITextField 限制为一位小数?文本字段用于输入价格,因此我不能允许超过一个小数点.如果我使用 Objective-C,我会使用以下代码:
How can I limit a UITextField to one decimal point with Swift? The text field is for entering a price, so I cannot allow more than one decimal point. If I was using Objective-C, I would have used this code:
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
NSString *newString = [textField.text stringByReplacingCharactersInRange:range withString:string];
NSArray *sep = [newString componentsSeparatedByString:@"."];
if([sep count] >= 2)
{
NSString *sepStr=[NSString stringWithFormat:@"%@",[sep objectAtIndex:1]];
return !([sepStr length]>1);
}
return YES;
}
但由于 Swift 使用范围的方式不同,我无法将此代码转换为 Swift.第一行给我一个错误,说 NSRange is not convertible to Range
But due a difference with how Swift uses ranges, I cannot convert this code to Swift. The first line gives me an error saying NSRange is not convertible to Range<String.Index>
我在看到答案之前就这样做了:
I ended up doing it like this before I saw the answer:
func textField(textField: UITextField!, shouldChangeCharactersInRange range: NSRange, replacementString string: String!) -> Bool {
let tempRange = textField.text.rangeOfString(".", options: NSStringCompareOptions.LiteralSearch, range: nil, locale: nil)
if tempRange?.isEmpty == false && string == "." {
return false
}
return true
}
我在另一个帖子上找到了这个.这个解决方案工作正常,但我不确定它是否是最好的方法,但它是一种简短而干净的方法.
I found this on a different post. This solution works fine but I'm not sure if it is the best way to do it but it is a short and clean way.
推荐答案
Swift 4 &Xcode 9.2
此解决方案只允许输入一个小数点,因此允许输入有效的双精度数.
This solution allows only one decimal point to be input, therefore allowing a valid double.
// Only allows one decimal point
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
let newString = (textField.text! as NSString).replacingCharacters(in: range, with: string)
let arrayOfString = newString.components(separatedBy: ".")
if arrayOfString.count > 2 {
return false
}
return true
}
这篇关于将 UITextField 限制为一位小数点 Swift的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!