gpt4 book ai didi

iphone - uitextfield positionFromPosition :offset not working emojis

转载 作者:可可西里 更新时间:2023-11-01 04:36:12 25 4
gpt4 key购买 nike

我正在尝试实现我自己的包含表情符号的键盘。为此,我在光标位置插入表情符号。

如果 UITextField 中不存在 4 字节的表情符号字符,则此方法可以正常工作。否则应用程序会崩溃。

我在这里发布插入代码。有人可以指出如何解决这个问题吗?

UITextField *field = self.textField;
UITextRange *range = field.selectedTextRange;
int pos = [field offsetFromPosition:field.beginningOfDocument toPosition:range.end];
NSString * firstHalfString = [field.text substringToIndex:pos];
NSString * secondHalfString = [field.text substringFromIndex:pos];
field.text = [NSString stringWithFormat: @"%@%@%@", firstHalfString, emoticon, secondHalfString];
UITextPosition *newPos = [field positionFromPosition:field.beginningOfDocument offset:pos + 1];
field.selectedTextRange = [field textRangeFromPosition:newPos toPosition:newPos];

如果文本中有表情符号,此行返回 nil:

UITextPosition *newPos = [field positionFromPosition:field.beginningOfDocument offset:pos + 1];

最佳答案

最后,我通过编写自己的长度和偏移量计算方法解决了这个问题,该方法将 4 字节字符计为 1 个字符,而不是两个。

@implementation NSString (UnicodeAdditions)
-(NSInteger)utf32length {
const char* bytes = [self UTF8String];
int length = [self lengthOfBytesUsingEncoding:NSUTF16StringEncoding];
int newLength = 0;
for (int i=0; i<length; i++) {
if (((unsigned char)bytes[i] >> 7) == 0b00000000) {
newLength++;
}
else if (((unsigned char)bytes[i] >> 5) == 0b00000110) {
newLength++;
i+=1;
}
else if (((unsigned char)bytes[i] >> 4) == 0b00001110) {
newLength++;
i+=2;
}
else if (((unsigned char)bytes[i] >> 3) == 0b00011110) {
newLength++;
i+=3;
}
}
return newLength;
}


-(NSInteger)utf32offsetWithOffset:(NSInteger)offset {
const char* bytes = [self UTF8String];
int length = [self lengthOfBytesUsingEncoding:NSUTF16StringEncoding];
int newLength = 0;
for (int i=0; i<length && offset!=0; i++) {
if (((unsigned char)bytes[i] >> 7) == 0b00000000) {
offset--;
newLength++;
}
else if (((unsigned char)bytes[i] >> 5) == 0b00000110) {
offset--;
newLength++;
i+=1;
}
else if (((unsigned char)bytes[i] >> 4) == 0b00001110) {
offset--;
newLength++;
i+=2;
}
else if (((unsigned char)bytes[i] >> 3) == 0b00011110) {
offset-=2;
newLength++;
i+=3;
}
}
return newLength;
}

@end

查看完整的博文 http://bit.ly/PT9VSz

关于iphone - uitextfield positionFromPosition :offset not working emojis,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12647071/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com