OC語言中,NSString類型的字符串,視英文字母和漢字都為一個長度(string.length把一個漢字也當做一個長度),而實際上,一個英文字母只占用1個字節,一個漢字占用2個字節。
有時又有需求,需要限定字節數目,而不是內容個數,就需要通過一些方法獲取到字符串的字節數。比如,限定10個字節,則最多可以輸入10個英文字母,或者5個漢字。
監聽textField的長度變化,就需要設置textField的代理。
但是有個bug,監聽內容變化的代理方法
1
|
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string |
在點擊鍵盤輸入是正常的,但如果不點擊鍵盤按鍵,拿漢字輸入舉例,輸入一個字后,鍵盤上面會出現與該字可能是詞語的字,點上面出現的字來輸入,就不會觸發上面的代理方法。
所以這個代理方法不能用,我們需要通過注冊textField的通知來監聽。
1
2
|
//注冊通知,textfield內容改變調用 [[NSNotificationCenter defaultCenter] addObserver:self selector: @selector (textFieldDidChange:) name:UITextFieldTextDidChangeNotification object:self.testTextField]; |
實現通知方法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
|
- ( void )textFieldDidChange:(NSNotification *)note{ UITextField *textField = note.object; //獲取文本框內容的字節數 int bytes = [self stringConvertToInt:self.testTextField.text]; //設置不能超過32個字節,因為不能有半個漢字,所以以字符串長度為單位。 if (bytes > 16 ) { //超出字節數,還是原來的內容 self.testTextField.text = self.lastTextContent; } else { self.lastTextContent = self.testTextField.text; } } //得到字節數函數 - ( int )stringConvertToInt:(NSString*)strtemp { int strlength = 0 ; char * p = ( char *)[strtemp cStringUsingEncoding:NSUnicodeStringEncoding]; for ( int i= 0 ; i<[strtemp lengthOfBytesUsingEncoding:NSUnicodeStringEncoding] ;i++) { if (*p) { p++; strlength++; } else { p++; } } return (strlength+ 1 )/ 2 ; } |
如果textField一開始就有內容,就要獲取到,用代理方法
1
2
3
4
5
|
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField { self.lastTextContent = textField.text; return YES; } |
以上所述是小編給大家介紹的IOS textField限制字節長度的相關內容,希望對大家有所幫助。