How can I limit a UITextField to one decimal point using Swift? The text box is for entering a price, so I cannot allow more than one decimal point. If I used Objective-C, I would use 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; }
But due to differences in 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>
EDIT: I ended up doing 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 in another post. This solution works fine, but I'm not sure if this is the best way to do this, but it is a short and clean way.
ios objective-c uitextfield swift
Shan
source share