1.ios中怎样限制textfield只能输入字母和数字
//设置键盘类型
self.textField.keyboardType = UIKeyboardTypeASCIICapable;
define kAlphaNum @"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
//判断是否是数字,不是的话就输入失败
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
NSCharacterSet *cs;
cs = [[NSCharacterSet characterSetWithCharactersInString:kAlphaNum] invertedSet];
NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""]; //按cs分离出数组,数组按@""分离出字符串
BOOLcanChange = [string isEqualToString:filtered];
return self.textField.text.length>=5?NO: canChange;
}
2.UITextField 限制只能输入中文
需求:限制UITextField只能输入中文,并且最大长度为4;
1,先声明一个UITextfield 变量;
@property (nonatomic, strong) UITextField *textField;
2,添加通知;
(void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFiledEditChanged:)name:UITextFieldTextDidChangeNotification object:self.textField];
}
3,在监听中,实现过滤非中文字符,并限制字符数量;
(BOOL)textFieldShouldReturn:(UITextField *)textField{
[textField resignFirstResponder];
//过滤非汉字字符
textField.text = [self filterCharactor:textField.text withRegex:@"[^\u4e00-\u9fa5]"];
if (textField.text.length >= 4) {
textField.text= [textField.textsubstringToIndex:4];
}
return NO;
}
(void)textFiledEditChanged:(id)notification{
UITextRangeselectedRange = self.textField.markedTextRange;
UITextPositionposition = [self.textField positionFromPosition:selectedRange.start offset:0];
if (!position) { //// 没有高亮选择的字
//过滤非汉字字符self.textField.text = [selffilterCharactor:self.textField.text withRegex:@"[^\u4e00-\u9fa5]"];if(self.textField.text.length >=4) {self.textField.text = [self.textField.text substringToIndex:4]; }
}else { //有高亮文字
//donothing
}
}
//根据正则,过滤特殊字符
(NSString)filterCharactor:(NSString)string withRegex:(NSString)regexStr{
NSStringsearchText = string;
NSErrorerror = NULL;
NSRegularExpressionregex = [NSRegularExpression regularExpressionWithPattern:regexStr options:NSRegularExpressionCaseInsensitive error:&error];
NSString *result = [regex stringByReplacingMatchesInString:searchText options:NSMatchingReportCompletion range:NSMakeRange(0, searchText.length) withTemplate:@""];
return result;
}
3.UITextField详解网站
http://www.cnblogs.com/xirui/p/5330289.html
网友评论