iOS 中文輸入長度控制

來源:互聯網
上載者:User

標籤:

當使用拼音IME時,該委託方法中的最後一個參數string接受的是輸入的字母,而不是選擇的漢字,造成的結果是,當想輸入文字“我在編程”,輸入拼音“wozaibiancheng”,每輸入一個字母便會進入委託方法,統計的字元長度是字母的長度,實際上漢字還未超過限制長度,但是字母的長度超過了導致無法繼續輸入。

中文控制輸入長度的方法如下:

1.註冊notification

[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(textFiledEditChanged:)                                                name:UITextFieldTextDidChangeNotification                                              object:self.customTextField];

  

2.實現監聽方法

-(void)textFiledEditChanged:(NSNotification *)obj{    UITextField *textField = (UITextField *)obj.object;        NSString *toBeString = textField.text;    NSString *lang = [[UIApplication sharedApplication] textInputMode].primaryLanguage; // 鍵盤輸入模式    if ([lang isEqualToString:@"zh-Hans"]) { // 簡體中文輸入,包括簡體拼音,健體五筆,簡體手寫        UITextRange *selectedRange = [textField markedTextRange];        //擷取高亮部分        UITextPosition *position = [textField positionFromPosition:selectedRange.start offset:0];        // 沒有高亮選擇的字,則對已輸入的文字進行字數統計和限制        if (!position) {            if (toBeString.length > 5) {                textField.text = [toBeString substringToIndex:5];            }        }        // 有高亮選擇的字串,則暫不對文字進行統計和限制        else{                    }    }    // 中文IME以外的直接對其統計限制即可,不考慮其他語種情況    else{        if (toBeString.length > 5) {            textField.text = [toBeString substringToIndex:5];        }      }  }

  

3.在dealloc中

-(void)dealloc{    [[NSNotificationCenter defaultCenter]removeObserver:self                                                   name:UITextFieldTextDidChangeNotification                                                 object:self.customTextField];}

  

 

同理,當使用UITextView時,如果要限制中文輸入,也是使用相同的方式。

[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(textViewEditChanged:)                                                name:UITextViewTextDidChangeNotification                                              object:myTextView];

  

iOS 中文輸入長度控制

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.