一種導致UITextView輸入中文卻先輸入拼音的解決思路



原因分析:最近測試發現在某個頁面的UITextView輸入中文時,會顯示輸入錯亂,如上圖所示。語言問題,輸入法等可能因素後,鎖定了問題的所在:   爲了實現字數限制 和禁止輸入換行符,我在回調函數裏寫了如下的坑爹代碼:


-(void)textViewDidChange:(UITextView *)textView

{

 textView.text =   [textView.text stringByReplacingOccurrencesOfString:@"\n" withString:@""];

    NSUInteger len = MIN([textView.text length],140);

   textView.text = [textView.text substringToIndex:len];

    countLabel.text = len>0?[NSString stringWithFormat:@"還可輸入%d",140-len]:@"最多50";

    countLabel.textColor = len<140?[UIColor colorWithWhite:0.5alpha:1]:[UIColor redColor];


}

問題就出在這兩句:

textView.text = [textView.text stringByReplacingOccurrencesOfString:@"\n" withString:@""];

 textView.text = [textView.text substringToIndex:len];

每次改變值的時候都去截取一次字符串,導致了中文的輸入問題。

參考解決方案:

- (void)textViewDidChange:(UITextView *)textView

{

    //不輸入換行

    if ([textView.texthasSuffix:@"\n"])

    {

        NSMutableString * textViewStr = [NSMutableStringstringWithString:textView.text];

        [textViewStr deleteCharactersInRange:NSMakeRange(textViewStr.length-1,1)];

        textView.text = textViewStr;

    }

    if (textView.text.length >=51)

    {

        textView.text = _remarkText;

        

        //切記:千萬不可使用下面的語句否則,當字數到50字符後,無法彈出鍵盤重新編輯。

        //      textView.editable = NO;

        return;

    }

    else

    {

        _remarkTextNumLab.textColor = [UIColorblackColor];

    }

    //不以空格開頭

    if ([textView.texthasPrefix:@" "])

    {

        NSMutableString * textViewStr = [NSMutableStringstringWithString:textView.text ];

        [textViewStr deleteCharactersInRange:NSMakeRange(0,1)];

        textView.text = textViewStr;

    }

    //不以三個空格結尾

    if ([textView.texthasSuffix:@"   "])

    {

        NSMutableString * textViewStr = [NSMutableStringstringWithString:textView.text];

        [textViewStr deleteCharactersInRange:NSMakeRange(textViewStr.length-2,1)];

        textView.text = textViewStr;

    }

    _remarkTextNumLab.text = [NSStringstringWithFormat:@"%ld/50",(long)(textView.text.length)];

    if ( [_remarkTextNumLab.textisEqualToString:@"50/50"])

    {

        _remarkTextNumLab.textColor = [UIColorredColor];

    }

    else

    {

        _remarkTextNumLab.textColor = [UIColorblackColor];

    }

    _remarkText = textView.text;

}


寫代碼時,要多留心分析,這樣寫能帶來什麼效果,有什麼不足之處,以及可能影響的地方,當代碼很多後,或者共用的代碼,一定要謹慎,儘可能的考慮到其他因素。

   多看多想多寫,讓隨手優化代碼,成爲一種習慣。




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章