How to set color of templated image in NSTextAttachment

后端 未结 7 1065
佛祖请我去吃肉
佛祖请我去吃肉 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 20:45

    The solution by @blazejmar works, but is unnecessary. All you need to do for this to work is set the color after the attributed strings have been connected. Here's an example.

    NSTextAttachment *attachment = [[NSTextAttachment alloc] init];
    attachment.image = [[UIImage imageNamed:@"ImageName"] imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
    
    NSAttributedString *attachmentString = [NSAttributedString attributedStringWithAttachment:attachment];
    
    NSString *string = @"Some text ";
    NSRange range2 = NSMakeRange(string.length - 1, attachmentString.length);
    
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:string];
    [attributedString appendAttributedString:attachmentString];
    [attributedString addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:range2];
    self.label.attributedText = attributedString;
    

提交回复
热议问题