UITextField詳解

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

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容