How to set color of templated image in NSTextAttachment

后端 未结 7 1103
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-29 20:30

How can I set the color of a templated image that is an attachment on an attributed string?

Background:

I\'ve got a UILabel and I\'m setting its attributedTe

7条回答
  •  余生分开走
    2020-12-29 21:05

    I found a better solution. Make sure that plain text is in the first item. If the NSTextAttachment (image) is the first item, you can insert a space string before the NSTextAttachment.

    // create image attachment
    NSTextAttachment *imageAttachment = [[NSTextAttachment alloc] init];
    imageAttachment.image = [[UIImage imageNamed:@"ImageName"] imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
    NSAttributedString *imageAttchString = [NSAttributedString attributedStringWithAttachment:attachment];
    
    // create attributedString
    NSString *string = @"Some text ";
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:string];
    
    // insert image 
    [attributedString insertAttributedString:imageAttchString atIndex:0];
    [attributedString insertAttributedString:[[NSAttributedString alloc] initWithString:@" "] atIndex:0];
    
    label.attributedText =  attributedString;
    
    // used
    label.textColor = [UIColor redColor];
    // or
    label.textColor = [UIColor greenColor];
    

提交回复
热议问题