2014-05-05 57 views
1

在这个伟大的社区的帮助下,我一直在为此工作了几天。按顺序显示编辑好的NSString

我有一个NSArray,我需要编辑NSStrings之内。我已经设法检测到字符串中的一个标记并使其变为粗体。但是现在我试图按照它们在NSArray内的顺序显示字符串,同时保持添加到特定字符串的粗体。

我可以显示单个粗体字符串'string',但我需要它是为了它在数组内。我知道stringByAppendingString但这会把它放在最后。

任何方向都会很棒。

for (NSString *testWord in legislationArray) { 
      if ([testWord rangeOfString:@"BOLDME"].location != NSNotFound) { 

      //Remove Marker 
      NSString *stripped = [testWord stringByReplacingOccurrencesOfString:@"BOLDME" withString:@""]; 

      //Get string and add bold 
      NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:stripped]; 

      NSRange selectedRange = [stripped rangeOfString:(stripped)]; 

      [string beginEditing]; 

      [string addAttribute:NSFontAttributeName 
          value:[UIFont fontWithName:@"Helvetica-Bold" size:18.0] 
          range:selectedRange]; 

      [string endEditing]; 

      //Where to go now with string? 

     } 
    } 
    cell.dynamicLabel.text = [legislationArray componentsJoinedByString:@"\n"]; 

编辑

基于答案下面我得到它的工作,不过大胆的方法调用此错误:

enter image description here

+0

您的其他问题不是错误 - 这是XCode在调试窗口中显示归因字符串的方式。我已将屏幕截图添加到我的答案中。 – Avt

回答

1

只需使用其他阵列。更改您的代码

NSMutableAttributedString *attrString = [[NSMutableAttributedString alloc] init]; 
for (NSString *testWord in legislationArray) { 
    if ([testWord rangeOfString:@"BOLDME"].location != NSNotFound) { 

     //Remove Marker 
     NSString *stripped = [testWord stringByReplacingOccurrencesOfString:@"BOLDME" withString:@""]; 

     //Get string and add bold 
     NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:stripped]; 

     NSRange selectedRange = [stripped rangeOfString:(stripped)]; 

     [string beginEditing]; 

     [string addAttribute:NSFontAttributeName 
         value:[UIFont fontWithName:@"Helvetica-Bold" size:18.0] 
         range:selectedRange]; 

     [string endEditing]; 

     //Where to go now with string? 
     [attrString appendAttributedString:string]; 
    } 
    else 
    { 
     [attrString appendAttributedString:[[NSAttributedString alloc] initWithString:testWord]]; 
    } 
    // NEW LINE 
    [attrString appendAttributedString:[[NSAttributedString alloc] initWithString:@"\n"]]; 
} 
cell.dynamicLabel.attributedText = attrString; 

UPDATE:

你额外的问题是不是一个错误 - 这是一种方式的XCode显示如何在调试窗口归因字符串: enter image description here

+0

这工作。但是,它会在更新的答案中显示的粗体上产生一个奇怪的错误。有什么建议么? – memyselfandmyiphone

+0

@memyselfandmyiphone我已经改进了答案。请检查一下。 – Avt

+0

看起来不错。现在唯一的问题是我已经失去了放置组件JoinedByString的位置:@“\ n”从阅读它的时候可以看出,这不是由于supportedString支持 – memyselfandmyiphone

3

componentsJoinedByString回报NSString,当你想要一个NSAttributedString。 另外,您正在将文本设置为等待NSStringcell.dynamicLabel.text)的接收器,其中您想要的应该是cell.dynamicLabel.attributedText

由于没有相当于componentsJoinedByStringNSAttributedString回报,你必须这样做的oldway,具有for循环,从初始化NSMutableAttributedString,并增加它的每个组件(你可以“改造”),以它。 Here是一个例子和相关的问题。