[英]using rangeOfString and textfield shouldChangeCharactersInRange - the delete character?
I'm using rangeofString and textfield: shouldChangeCharactersinRange: to restrict the types of keystrokes that will be valid in a textfield. 我正在使用rangeofString和textfield:shouldChangeCharactersinRange:来限制将在文本字段中有效的击键类型。
-(BOOL) textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
NSString *includeString = @"1234567890-()+" ;
if ([includeString rangeOfString:string].location == NSNotFound) {
return NO;
}
return YES;
} }
this works fine EXCEPT i now can't use the delete key. 除了我现在不能使用删除键之外,这还可以。 Any ideas how to represent the delete key to add it to the includeString?
任何想法如何表示删除键以将其添加到includeString?
I tried 我试过了
`NSString *includeString = @"1234567890-()+\\b" `NSString * includeString = @“ 1234567890-()+ \\ b”
but that didn't work - neither did it allow the \\ or b characters to appear which i thought odd 但这没有用-我也认为奇怪的\\或b字符也没有出现
Thanks 谢谢
The replacement string string
is empty when characters are deleted. 删除字符时,替换字符串
string
为空 。 Since rangeOfString:string
returns NSNotFound
for an empty string, you have to check for that situation first: 由于
rangeOfString:string
返回一个空字符串的NSNotFound
,因此您必须首先检查这种情况:
-(BOOL) textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
if ([string length] == 0)
return YES;
NSString *includeString = @"1234567890-()+" ;
if ([includeString rangeOfString:string].location == NSNotFound) {
return NO;
}
return YES;
}
Update: As @rmaddy correctly pointed out, the above method fails if more than one character is pasted into the text field. 更新:正如@rmaddy正确指出的,如果将多个字符粘贴到文本字段中,则上述方法将失败。 The following method checks if all characters of the replacement string are valid.
以下方法检查替换字符串的所有字符是否有效。 (There are probably many solutions, this is only one of them.)
(可能有很多解决方案,这只是其中之一。)
-(BOOL) textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
static NSString *includeString = @"1234567890-()+";
NSCharacterSet *includeSet = [NSCharacterSet characterSetWithCharactersInString:includeString];
if ([[string stringByTrimmingCharactersInSet:includeSet] length] > 0)
return NO;
return YES;
}
Note that the empty string does not need to be handled separately anymore. 请注意,不再需要单独处理空字符串。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.