问题描述
我有一个 UILabel
,我想在其中显示一个Unicode字符。以下工作:
I have a UILabel
in which I want to display a Unicode character. The following works:
label.text = @"\U000025A0";
现在我想动态生成一个十进制数的Unicode字符,如下所示:
Now I want to dynamically generate the Unicode character from a decimal number as follows:
label.text = NSString stringWithFormat:@"\U%08x",9632];
Xcode编译器失败,出现以下错误:
Xcode compiler fails with the following error:
\U used with no following hex digits
是有一种方法可以将十进制数9632转换为Unicode,然后将其显示在 UILabel
?
Is there a way to convert the decimal number 9632 to Unicode and then display it in a UILabel
?
推荐答案
我有同样的问题来显示entypo字体的特殊字符,所以我实现了我自己的 EntypoStringCreator
类(有一些SO的帮助)。这里是用于将unicode数字转换为nsstring的方法:
I had a same issue to display entypo Font special character, so I implemented my own EntypoStringCreator
class (with some help from SO). Here are the method used to convert a unicode number to a nsstring:
.h
@interface EntypoStringCreator : NSObject
+(NSString *)stringForIcon:(UTF32Char)char32;
@end
.m
@implementation EntypoStringCreator
+(NSString *)stringForIcon:(UTF32Char)char32
{
if ((char32 & 0xFFFF0000) != 0)
return [self stringFromUTF32Char:char32];
else
return [self stringFromUTF16Char:(UTF16Char)(char32&0xFFFF)];
}
+(NSString *)stringFromUTF32Char:(UTF32Char)char32
{
char32 -= 0x10000;
unichar highSurrogate = (unichar)(char32 >> 10); // leave the top 10 bits
highSurrogate += 0xD800;
unichar lowSurrogate = char32 & 0x3FF; // leave the low 10 bits
lowSurrogate += 0xDC00;
return [NSString stringWithCharacters:(unichar[]){highSurrogate, lowSurrogate} length:2];
}
+(NSString *)stringFromUTF16Char:(UTF16Char)char16
{
return [NSString stringWithCharacters:(unichar[]){char16} length:1];
}
@end
这篇关于ios - 动态创建并显示unicode字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!