2013-09-30 37 views
0

我有一個NSString它包含unicode字符本身。Unicode字符在NSAttributedString中丟失

例:

It's blank.\u000e test \u000f 

NSString的長度是19

這裏,\u000e\u000f是Unicode字符。

我將上述NSString轉換爲NSMutableAttributedString,我已經應用了一些字體權重屬性。然後,我登錄了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字符丟失。我不知道我的代碼有什麼問題。

+1

執行字符'0x000e'和'0x000f'有字形?他們似乎是控制角色。 – trojanfoe

回答

2

當您嘗試創建包含某些Unicode字符的某些特定字體系列(例如:HelveticaNeue-Bold)的NSMutableAttributedString時,它將用空字符串替換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);