不同的字体在一个字符串数组中的

问题描述:

比方说,我有这样的:不同的字体在一个字符串数组中的

self.dictionary = [NSMutableArray arrayWithObjects: 
          @"blah", 
          @"blah", 
          @"blah (blah)", 
          @"blah", 
          @"blah", 
          nil]; 

在第三个对象,我想有第一个“嗒嗒”用较大的字体大小和黑色字体 - 颜色。但是,我希望第二个“blah”的括号具有较小的尺寸和灰色。我会如何去做这件事?它甚至有可能吗?

您想使用NSMutableAttributedString

您可以简单地连接所有你的字符串和每个子字符串,然后调用- setAttributes:range:来表示你想要的属性。

NSString不允许你有特定的风格。如果你的字符串需要有风格/属性,你将不得不使用NSAttributedString。

现在你只存储NSString对象。 NSString没有附加任何字体。如果你想保持字体的信息 - 你可以在NSAttributedString类看一看 - https://developer.apple.com/Library/ios/documentation/Cocoa/Reference/Foundation/Classes/NSAttributedString_Class/index.html

所以,你的代码看起来像:

self.items = @[ 
[[NSAttributedString alloc] initWithString: @"bla" attributes: @{ 
    NSFontAttributeName: [UIFont systemFontOfSize: 12.0], 
    NSForegroundColorAttributeName: [UIColor blackColor] 
}], 
[[NSAttributedString alloc] initWithString: @"bla" attributes: @{ 
    NSFontAttributeName: [UIFont systemFontOfSize: 14.0], 
    NSForegroundColorAttributeName: [UIColor grayColor] 
}] 
]; 

试试下面的代码: -

NSArray *yourArr= @[@"blah", 
         @"blah", 
         @"blah (blah)", 
         @"blah", 
         @"blah"]; 


    for (NSString *word in yourArr) 
    { 
     if ([word isEqualToString:@"blah (blah)"]) 
     { 

      [yourAtt appendAttributedString:[[NSAttributedString alloc]initWithString:[word componentsSeparatedByString:@" "][0] attributes:@{NSFontAttributeName:[NSFont boldSystemFontOfSize:18]}]]; 
      [yourAtt appendAttributedString:[[NSAttributedString alloc]initWithString:@" "]]; 
      [yourAtt appendAttributedString:[[NSAttributedString alloc]initWithString:[word componentsSeparatedByString:@" "][1] attributes:@{NSFontAttributeName:[NSFont boldSystemFontOfSize:14],NSForegroundColorAttributeName:[NSColor grayColor]}]]; 
     } 
     else 
     { 
      [yourAtt appendAttributedString:[[NSAttributedString alloc]initWithString:word]]; 
     } 
     [yourAtt appendAttributedString:[[NSAttributedString alloc]initWithString:@",\n"]]; 

    } 
    self.yourAttStr=yourAtt; 

enter image description here