Search code examples
iosobjective-cnsstringnsattributedstring

NSMutableAttributedString contains NSMutableAttributedString and NSString


NSTextAttachment *attachment = [[NSTextAttachment alloc] init];
attachment.image = [UIImage imageNamed:@"smiley_0.png"];
attachment.bounds = CGRectMake(0, 0, 22, 22);
NSMutableAttributedString *attributedString = [[NSAttributedString attributedStringWithAttachment:attachment] mutableCopy];
[aLabel setAttributedText:attributedString];

Using code above, aLabel can display a image(smiley_0.png) correctly, now I want to append a string to the aLabel, any idea?


Solution

  • Try to use appendAttributedString of NSMutableAttributedString to your attributedString as below

    NSTextAttachment *attachment = [[NSTextAttachment alloc] init];
    attachment.image = [UIImage imageNamed:@"smiley_0.png"];
    attachment.bounds = CGRectMake(0, 0, 22, 22);
    NSMutableAttributedString *appendedString=[[NSMutableAttributedString alloc]initWithString:@"yourString"];
    NSMutableAttributedString *attributedString = [[NSAttributedString attributedStringWithAttachment:attachment] mutableCopy];
    [attributedString appendAttributedString:appendedString];
    [aLabel setAttributedText:attributedString];
    

    Hope it helps you....!