【问题标题】:How can I word wrap with NSMutableAttributedString?如何使用 NSMutableAttributedString 自动换行?
【发布时间】:2014-09-28 13:34:01
【问题描述】:
NSArray *myArray = @[@"1st:array1", 
                     @"2nd:array2", 
                     @"3rd:array3"
                    ];
NSString *labelString = [myArray componentsJoinedByString:@"\n"];

在此代码中labelString可以换行。
但是如果像这样使用 NSMutableAttributedString

NSAttributedString *resultString = [resultArray componentsJoinedByString:@"\n"];

它不能被@"\n" 加入。还有其他方法吗?谢谢。

【问题讨论】:

  • @Larme 嗯,有点难以理解,但我会尝试一下。谢谢。
  • 这并不难。您只需要了解componentsJoinedByString: 背后的算法/逻辑,并根据您的需要进行调整。

标签: objective-c nsstring nsarray nsattributedstring nsmutableattributedstring


【解决方案1】:

这并不难。你只知道一件事。
AttributedString 可能不能有\n。因此,您只需将 \n 放入 NSString。
只需从这个 NSString 制作 NSAttributedString。
这里是这段代码。我希望这段代码对您的工作有所帮助。

NSString *commentString;    
NSMutableArray *resultArray = [[NSMutableArray alloc]initWithCapacity:50];    

for (InstagramComment *comment in comments) {
    commentString = [NSString stringWithFormat:@"%@:%@\n", comment.user.username, comment.text];

    NSMutableAttributedString *styledCommentString = [[NSMutableAttributedString alloc]initWithString:commentString];
    [resultArray addObject:styledCommentString];
}

NSMutableAttributedString *resultString = [[NSMutableAttributedString alloc]init];

for (int i = 0; i < resultArray.count; ++i) {
    [resultString appendAttributedString:[resultArray objectAtIndex:i]];
} [cell.comment setAttributedText:resultString];

【讨论】:

    猜你喜欢
    • 2012-08-18
    • 2013-02-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-25
    • 2017-11-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多