如何使用NSMutableAttributedString进行自动换行?

时间:2014-09-28 13:34:01

标签: objective-c nsstring nsarray nsattributedstring nsmutableattributedstring

NSArray *myArray = @[@"1st:array1", 
                     @"2nd:array2", 
                     @"3rd:array3"
                    ];
NSString *labelString = [myArray componentsJoinedByString:@"\n"];

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

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

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

1 个答案:

答案 0 :(得分:-2)

这并不困难。你只知道一件事 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];