【每日·槽】第4话 -- UITextField 中文字符的长度检测问题

本节目纯属扯淡,如有得罪,还请。。。。。。有本事你来打我呀!!!

【每日·槽】第4话 – UITextField 中文字符的长度检测问题
每日槽,厚德载“雾”,自强不“吸”。据说本月29-31号放假啊亲!

问题描述:将 UITextField 长度限制为6,手动输入中文没问题可以输入6个中文,但使用setText(“一二三四五六”)却只能显示“一二”。这是为何?

原来手动输入调用的是cocos2d里的 TextFieldTTF::insertText ,里面会将1个中文算作一个长度。看代码:
static int _calcCharCount(const char * text)
{
int n = 0;
char ch = 0;
while ((ch = *text))
{
CC_BREAK_IF(! ch);

    if (0x80 != (0xC0 & ch))
    {
        ++n;
    }
    ++text;
}
return n;

}

如此高端大气上档次 0x80和0xC0是啥意思呢?我不懂搜了下
http://stackoverflow.com/questions/3911536/utf-8-unicode-whats-with-0xc0-and-0x80/3911566 里面讲的很详细。

我们再来看看 CocoStudio 里的 UITextField 的 setText,
void TextField::setText(const std::string& text)
{
std::string strText(text);
if(isMaxLengthEnabled())
{
strText = strText.substr(0, getMaxLength());
}
……
}

text是三个汉字的utf8编码 :"\xe4\xb8\x87\xe5\x8d\x83\xe7\x81\xb5" ,长度为9,获取最大长度为6,直接把最后一个字给截取了。

原来如此啊,UITextField的罪孽又加深了一层 !其他罪过请参考

每日·槽】第3话–TextField的七宗罪 http://www.cocoachina.com/bbs/read.php?tid=182207

哎,屌丝何苦为难屌丝??!!

本屌班门弄斧临时改了一下
// 截取字符长度
std::string TextField::substr(const char * text)
{
int maxLength = getMaxLength();
int n = 0;
char ch = 0;
std::string newText = “”;
while ((ch = *text))
{
CC_BREAK_IF(! ch);

    if (0x80 != (0xC0 & ch))
    {
        ++n;
        if (n > maxLength) {
            return newText;
        }
    }
    newText += ch;
    ++text;
}
return newText;

}

setText 里改为
if(isMaxLengthEnabled())
{
strText = this->substr(text.c_str());
// strText = strText.substr(0, getMaxLength());
}

希望 CocoStudio 的开发团队能够沉下心来,不要心浮气躁,多向Cocos2D学习,不说功能做的多么nb,先能用再说吧!


往期回顾:

【 每日·槽】第1话 – 论setEnabled和setVisible
http://www.cocoachina.com/bbs/read.php?tid=181496

【 每日·槽】第2话 – 模态窗口的制作
http://www.cocoachina.com/bbs/read.php?tid=181959

【 每日·槽】第3话–UITextField的七宗罪 http://www.cocoachina.com/bbs/read.php?tid=182207

楼主您好,目前这个问题是已经解决的,修复后的版本将在下月中上旬发布,请及时关注官方动态。

LZ研究的很细致啊 顶起~

:7:骚年 好功夫

看到版主头像我的小心脏又怦怦乱跳了 :866:

骚年,来一发不? :7:

恭喜楼主吐槽成功!