iOS 限制輸入字數完美解決方案

來源:互聯網
上載者:User

標籤:

關於限制輸入字數以前也做過,網上也很多方法。

但都不夠完美,以前的測試人員也沒千方百計的挑毛病,所以就糊弄過去了。

現在這個項目的測試人員為了找bug真是無所不用其極。。。。

1.一般方法就是通過UITextField的代理方法

#pragma mark - UITextFieldDelegate- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{    if (textField == self.textFieldName) {        if (string.length == 0) return YES;        NSInteger existedLength = textField.text.length;        NSInteger selectedLength = range.length;        NSInteger replaceLength = string.length;        if (existedLength - selectedLength + replaceLength > 20) {            return NO;        }    }    return YES;}

but這個方法還是有bug的。。。這個方法很容易被中文的聯想、粘貼等方式突破限制長度。

2.給UITextField加事件,然後在事件裡截取至最大長度

[self.textFieldName addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];- (void)textFieldDidChange:(UITextField *)textField{    if (textField == self.textFieldName) {        if (textField.text.length > 15) {            textField.text = [textField.text substringToIndex:15];        }    }}

你以為這樣搞定了中文聯想、粘貼的bug,就高枕無憂了嗎。。。這方法還是有bug的,如果輸入至還剩一個字元時,再輸入Emoji呢?Emoji佔2個字元,會被截得出現半個Emoji的情況,含半個Emoji的字串在URL編碼時會變為nil。

3.限制輸入字數完美解決方案

其實就是在方案2上做了調整

- (void)textFieldDidChange:(UITextField *)textField{    if (textField == self.textFieldName) {        if (textField.text.length > 15) {            //Emoji佔2個字元,如果是超出了半個Emoji,用15位置來截取會出現Emoji截為2半        //超出最大長度的那個字元序列(Emoji算一個字元序列)的range        NSRange range = [textField.text rangeOfComposedCharacterSequenceAtIndex:15];            textField.text = [textField.text substringToIndex:range.location];        }    }}

 

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.