iOS动态Unicode NSString用于字体图标

4
我在iOS中使用了一些需要通过其Unicode字符串来识别图标的字体图标。我希望能够从服务器以JSON格式检索代码,并动态创建此Unicode字符串以检索字体图标并将其放入标签等中。但是,我在转换方面遇到了问题。根据以下代码,有什么想法吗?
这里是工作示例,其中“E539”是从服务器接收到的字符串。我可以硬编码它并且它可以工作,但是动态创建它并不那么容易。
[iconLabel materialIconWithUnicodeStr:[NSString stringWithFormat:@"\uE539"]];

这些东西不起作用:

[iconLabel materialIconWithUnicodeStr:[NSString stringWithFormat:@"\u%@", @"E539"]];
[iconLabel materialIconWithUnicodeStr:[NSString stringWithFormat:@"\\u%@", @"E539"]];

我找到了一个类,可以使用UTF32Char生成Unicode。这行代码能够工作,但不是整个解决方案。
[iconLabel materialIconWithUnicodeStr:[EntypoStringCreator stringForIcon:0xE539]]

尝试根据我找到的代码进行拼接,几乎可以工作,但是生成了错误的Unicode编码。我不知道为什么。
NSString  *unicodeStr = @"E539";

// attempt to convert E539 -> 0xE539
UTF32Char outputChar;
if ([unicodeStr getBytes:&outputChar maxLength:4 usedLength:NULL encoding:NSUTF32LittleEndianStringEncoding options:0 range:NSMakeRange(0, 1) remainingRange:NULL]) {
    outputChar = NSSwapLittleIntToHost(outputChar); // swap back to host endian
    // outputChar now has the first UTF32 character
}

// this does not give the correct icon at all
[iconLabel [EntypoStringCreator stringForIcon:outputChar]];

为什么不将十六进制代码转换为数字,并使用“%C”将其附加到字符串中呢? - Eiko
1个回答

3
你的 materialIconWithUnicodeStr: 方法正在寻找一个包含实际 Unicode 字符编码的字符串。你的可行示例之所以能够实现这一点,是因为转义序列在编译时工作,以生成字符。但是,无论如何格式化或双重转义,您的不起作用的示例都会失败,因为 \u 转义是一种仅在编译时生效而在运行时无法生效的转义。
你需要一种方法,可以从你已有的十六进制值中,在运行时获取 Unicode 字符。
unsigned c = 0;
NSScanner *scanner = [NSScanner scannerWithString:@"E539" ];
[scanner scanHexInt: &c];
NSString* unicodeStr = [NSString stringWithFormat: @"%C", (unsigned short)c];

[iconLabel materialIconWithUnicodeStr: unicodeStr];

运行得非常完美!! - Miro

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接