0

我有一个NSString它本身包含 unicode 字符。

前任:

It's blank.\u000e test \u000f

NSString长度是19

在这里,\u000e\u000f是 Unicode 字符。

我将上述内容转换NSString为 anNSMutableAttributedString并应用了一些 font-weight 属性。然后,我记录NSMutableAttributedString并获得以下输出。

我的示例代码:

NSString *contAtRng = @"It's blank.\u000e test \u000f";
NSMutableAttributedString *attrText = [[NSMutableAttributedString alloc] initWithString:contAtRng];
NSMutableDictionary *attrs = [NSMutableDictionary new];
[attrs setObject:[UIFont fontWithName:@"HelveticaNeue-Bold" size:10] forKey:NSFontAttributeName];
[attrText setAttributes:attrs range:NSMakerange(0,contAtRng.length)];
NSLog(@"String : %@",attrText);

输出:

It's blank. test {
NSFont = "<UICTFont: 0x16d22250> font-family: \"Helvetica Neue\"; font-weight: bold; font-style: normal; font-size: 10.00pt";}

现在的NSMutableAttributedString长度是17

结果,缺少 Unicode 字符。我不知道我的代码做错了什么。

4

1 回答 1

2

当您尝试使用包含一些 unicode 字符的NSMutableAttributedString特定字体系列(例如:)创建时HelveticaNeue-Bold,它将用空字符串替换 unicode 字符并提供剩余的字符串。

所以,我们会错过 unicode 字符。

为避免此问题,请在设置字体系列时跳过 unicode 字符NSMutableAttributedString

这是我的代码:

NSString *contAtRng = @"It's blank.\u000e test \u000f";
NSMutableAttributedString *attrText = [[NSMutableAttributedString alloc] initWithString:contAtRng];
NSMutableDictionary *attrs = [NSMutableDictionary new];  
[attrs setObject:[UIFont fontWithName:@"HelveticaNeue-Bold" size:10] forKey:NSFontAttributeName];
[attrText setAttributes:attrs range:NSMakerange(0,11)];
[attrText setAttributes:attrs range:NSMakerange(12,6)];
NSLog(@"String : %@",attrText);
于 2013-12-10T08:04:15.277 回答