1.ios中怎樣限制textfield只能輸入字母和數(shù)字
//設(shè)置鍵盤(pán)類(lèi)型
self.textField.keyboardType = UIKeyboardTypeASCIICapable;
define kAlphaNum @"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
//判斷是否是數(shù)字,不是的話(huà)就輸入失敗
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
NSCharacterSet *cs;
cs = [[NSCharacterSet characterSetWithCharactersInString:kAlphaNum] invertedSet];
NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""]; //按cs分離出數(shù)組,數(shù)組按@""分離出字符串
BOOLcanChange = [string isEqualToString:filtered];
return self.textField.text.length>=5?NO: canChange;
}
2.UITextField 限制只能輸入中文
需求:限制UITextField只能輸入中文,并且最大長(zhǎng)度為4;
1,先聲明一個(gè)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,在監(jiān)聽(tīng)中,實(shí)現(xiàn)過(guò)濾非中文字符,并限制字符數(shù)量;
(BOOL)textFieldShouldReturn:(UITextField *)textField{
[textField resignFirstResponder];
//過(guò)濾非漢字字符
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) { //// 沒(méi)有高亮選擇的字
//過(guò)濾非漢字字符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
}
}
//根據(jù)正則,過(guò)濾特殊字符
(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詳解網(wǎng)站
http://www.cnblogs.com/xirui/p/5330289.html