NSAttributedString *attributesStr = [self attributeWithString:@"小小的人啊 假不正經啊 天天就愛窮開心啊" imageNames:@[@"testImage",@"testImage",@"testImage",@"testImage"] imageBounds:CGRectMake(0, -5, 40, 40) font:[UIFont systemFontOfSize:30] fontColor:[UIColor greenColor]];
self.textLabel.attributedText = attributesStr;
複製程式碼
- (NSAttributedString *)attributeWithString:(NSString *)string
imageNames:(NSArray *)imageNames
imageBounds:(CGRect)imageBounds
font:(UIFont *)font
fontColor:(UIColor *)fontColor
{
NSDictionary *attributes = @{
NSForegroundColorAttributeName:fontColor,
NSFontAttributeName:font
};
NSMutableAttributedString *attributeString = [[NSMutableAttributedString alloc] initWithString:string attributes:attributes];
NSTextAttachment *attach = [[NSTextAttachment alloc] init];
attach.bounds = imageBounds;
NSAttributedString *imageString = [NSAttributedString attributedStringWithAttachment:attach];
for (NSString *imageName in imageNames)
{
attach.image = [UIImage imageNamed:imageName];
[attributeString insertAttributedString:[[NSAttributedString alloc] initWithString:@" "] atIndex:0];
[attributeString insertAttributedString: imageString atIndex:0];
[attributeString addAttribute:NSKernAttributeName value:@(15) range:NSMakeRange(0,2)];
}
return attributeString;
}
複製程式碼