如何将NSMutableAttributedString存储到数组中

时间:2015-09-22 18:24:33

标签: ios objective-c nsmutableattributedstring

我正在尝试自定义一个字符串" Add as Event 1"(" Event 1"是粗体)然后将字符串存储到一个可变数组中。这是我的代码:

public async void Foo(int limit){
    await DoStuffForAWhile(limit);
    TheBoundProperty = "But this is!";
}

public async Task DoStuffForAWhile(int limit)
{
  TheBoundProperty = "This is not shown.";

  DateTime start = DateTime.Now;
  TimeSpan elapsed;
  do
  {
    elapsed = new TimeSpan(DateTime.Now.Ticks - start.Ticks);
    TheBoundProperty = "Neither is this.";
    await Task.Delay(1000); //1 sec delay
  } while (elapsed.TotalSeconds < limit);
}

但在eventsData数组中,我发现存储了attrString1的所有约束。但是我只需要数组中的自定义字符串,因为我稍后会将值传递给UITableviewCell中的标签。这是我存储在数组中的内容:

NSString *string1 = @"Add as Event 1";
NSMutableArray *eventsData;
NSMutableAttributedString *attrString1 = [[NSMutableAttributedString alloc]initWithString:string1];
CTFontRef helvetica = CTFontCreateWithName(CFSTR("Avenir-Book"), 14.0, NULL);
CTFontRef helveticaBold = CTFontCreateWithName(CFSTR("Avenir-Heavy"), 14.0, NULL);
[attrString1 addAttribute:(id)kCTFontAttributeName
               value:(__bridge id)helvetica
               range:NSMakeRange(0, [attrString1 length])];
[attrString1 addAttribute:(id)kCTFontAttributeName
               value:(__bridge id)helveticaBold
               range:NSMakeRange(7, 7)];
eventsData = [[NSMutableArray alloc] initWithObjects: attrString1, nil];

谁能告诉我怎么做?非常感谢。

1 个答案:

答案 0 :(得分:0)

我认为你非常接近你想要的东西。创建字符串并将其添加到当前拥有的数组***。之后,如果你想使用普通字符串或属性字符串,你可以这样做......

// assume eventsData has at least one attributed string in it
NSMutableAttributedString *attributedString = eventsData[0];

// assign the plain string to a label like this
myLabel.text = attributedString.string;

// assign it with attributes to a label like this
myLabel.attributedText = attributedString;

***有一些机会可以改进创建属性字符串和eventsData数组的代码,但我认为这是主要问题的附带条件。