3

我有一个NSString这样的charactercode0x1F514。我想把NSString它添加到另一个NSString,但不是用它的字面值,而是隐藏在它后面的图标。在这种情况下,一个铃铛的表情符号。

我怎样才能轻松地将其转换NSString为显示表情符号而不是字符代码?

4

2 回答 2

2

这样的事情会做:

NSString *c = @"0x1F514";

unsigned intVal;
NSScanner *scanner = [NSScanner scannerWithString:c];
[scanner scanHexInt:&intVal];

NSString *str = nil;
if (intVal > 0xFFFF) {
    unsigned remainder = intVal - 0x10000;
    unsigned topTenBits = (remainder >> 10) & 0x3FF;
    unsigned botTenBits = (remainder >>  0) & 0x3FF;

    unichar hi = topTenBits + 0xD800;
    unichar lo = botTenBits + 0xDC00;
    unichar unicodeChars[2] = {hi, lo};
    str = [NSString stringWithCharacters:unicodeChars length:2];
} else {
    unichar lo = (unichar)(intVal & 0xFFFF);
    str = [NSString stringWithCharacters:&lo length:1];
}

NSLog(@"str = %@", str);

根本@"\u1f514"不起作用的原因是因为这些\u值不能在 BMP 之外,即 >0xFFFF,即 >16 位。

因此,我的代码所做的是检查该场景并使用相关的代理对魔术来制作正确的字符串。

希望这实际上是您想要的并且有意义!

于 2012-10-18T20:23:46.070 回答
1

If your NSString contains this "bell" character, then it does. You just append strings the usual way, like with stringByAppendingString.

The drawing of a bell instead of something denoting an unknown character is a completely separate issue. Your best bet is to ensure you're not using CoreText for drawing this, as it's been reported elsewhere, and I've seen it myself at work, that various non-standard characters may not work when printed that way. They do work, however, when printed with UIKit (that should be standard UI components, UIKitAdditions, and so on).

If using CoreText, you might get a bit lucky if you disable some text properties for the string with this special character, or choose appropriate font (but I won't help you here; we decided to leave the issue as Won't fix).

Having said that, the last time I was dealing with those was in pre-iOS 6 days...

Summary: your problem is not appending strings, but how you draw them.

于 2012-10-18T20:36:42.760 回答