How to set color of templated image in NSTextAttachment

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

    It seems that there's a bug in UIKit. There's a workaround for that ;]

    For some reason you need to append empty space before image attachment to make it work properly with UIImageRenderingModeAlwaysTemplate.

    So your snippet would look like that (mine is in ObjC):

    - (NSAttributedString *)attributedStringWithValue:(NSString *)string image:(UIImage *)image {
        NSTextAttachment *attachment = [[NSTextAttachment alloc] init];
        attachment.image = image;
    
        NSAttributedString *attachmentString = [NSAttributedString attributedStringWithAttachment:attachment];
        NSMutableAttributedString *mutableAttributedString = [[NSMutableAttributedString alloc] initWithAttributedString:[[NSAttributedString alloc] initWithString:@" "]];
        [mutableAttributedString appendAttributedString:attachmentString];
        [mutableAttributedString addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:0] range:NSMakeRange(0, mutableAttributedString.length)]; // Put font size 0 to prevent offset
        [mutableAttributedString addAttribute:NSForegroundColorAttributeName value:[UIColor whiteColor] range:NSMakeRange(0, mutableAttributedString.length)];
        [mutableAttributedString appendAttributedString:[[NSAttributedString alloc] initWithString:@" "]];
    
        NSAttributedString *ratingText = [[NSAttributedString alloc] initWithString:string];
        [mutableAttributedString appendAttributedString:ratingText];
        return mutableAttributedString;
    }
    

提交回复
热议问题