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