我有一个 textfield ,我希望在其中输入以下格式的文本:
#### 1234
我知道这应该在 textfield .nut 的 shouldChangeCharactersInRange delegate 方法中完成我无法理解如何在每个字符上实现条件.请提出您的建议。提前致谢!
Best Answer-推荐答案 strong>
有助于验证您的需求的表达式可能是:
^[a-z]{2}\s\d{4}\s\d{4}$
这里:
^ - Shows start of string
[a-z]{2} - Shows any character between a-z exactly 2 times
\s - Shows white space character one time.
\d{4} - Shows any digit from 0-9, exactly 4 times.
$ - Shows end of string
一个解决方法的例子可能是这样,这里棘手的部分是允许正在构建的字符串:
- (BOOL)textFieldUITextField *)textField shouldChangeCharactersInRangeNSRange)range replacementStringNSString *)string
{
NSError *error = NULL;
NSRegularExpression *regex = nil;
NSMutableString *combinedText = [textField.text mutableCopy];
[combinedText replaceCharactersInRange:range withString:string];
switch (combinedText.length) {
case 1:
case 2:
regex = [NSRegularExpression regularExpressionWithPattern:[NSString stringWithFormat"^[a-z]{%ld}", (long)combinedText.length] options:NSRegularExpressionCaseInsensitive error:&error];
break;
case 3:
regex = [NSRegularExpression regularExpressionWithPattern"^[a-z]{2}\\s" options:NSRegularExpressionCaseInsensitive error:&error];
break;
case 4:
case 5:
case 6:
case 7:
regex = [NSRegularExpression regularExpressionWithPattern:[NSString stringWithFormat"^[a-z]{2}\\s\\d{%ld}", (long)combinedText.length - 3] options:NSRegularExpressionCaseInsensitive error:&error];
break;
case 8:
regex = [NSRegularExpression regularExpressionWithPattern"^[a-z]{2}\\s\\d{4}\\s" options:NSRegularExpressionCaseInsensitive error:&error];
break;
case 9:
case 10:
case 11:
case 12:
regex = [NSRegularExpression regularExpressionWithPattern:[NSString stringWithFormat"^[a-z]{2}\\s\\d{4}\\s\\d{%ld}$", (long)combinedText.length - 8] options:NSRegularExpressionCaseInsensitive error:&error];
break;
default:
return false;
}
if(error) return false;
NSUInteger numberOfMatches = [regex numberOfMatchesInString:combinedText options:0 range:NSMakeRange(0, combinedText.length)];
return numberOfMatches > 0 || string.length == 0;
}
希望有帮助!
关于ios - 输入的 Textfield.text 应具有特定格式,我们在Stack Overflow上找到一个类似的问题:
https://stackoverflow.com/questions/43625511/
|