Search code examples
objective-cnsstringnsarraynsattributedstringnsmutableattributedstring

How can I word wrap with NSMutableAttributedString?


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

In this codelabelStringcan be word wrapped.
But if use NSMutableAttributedString like this

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

it can't be joined by @"\n". Any other method is existed? Thanks.


Solution

  • It's not difficult. You just know one thing.
    AttributedString can't have \n maybe. So you just put \n in NSString.
    And just make NSAttributedString from this NSString.
    Here this code. I hope this code help your work.

    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];