一种导致UITextView输入中文却先输入拼音的解决思路

来源:互联网 发布:哪里有淘宝教学视频 编辑:程序博客网 时间:2024/06/08 11:20



原因分析:最近测试发现在某个页面的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;

}


写代码时,要多留心分析,这样写能带来什么效果,有什么不足之处,以及可能影响的地方,当代码很多后,或者共用的代码,一定要谨慎,尽可能的考虑到其他因素。

   多看多想多写,让随手优化代码,成为一种习惯。




0 0
原创粉丝点击