ios的图文混排有两种方案
1.使用NSTextAttachment
- (NSMutableAttributedString*)createTextImage:(NSString*)text witImage:(NSString*)imageName{
NSMutableAttributedString *scaleStr= [[NSMutableAttributedString alloc] initWithString:text attributes:@{NSForegroundColorAttributeName:[UIColor whiteColor], NSFontAttributeName:PingFangBold(18)}];
//添加图片
NSTextAttachment *textAttachment = [[NSTextAttachment alloc] init];
textAttachment.bounds = CGRectMake(0, 2, 12, 7); //根据图片位置进行调整
textAttachment.image = [UIImage imageNamed:imageName];
NSAttributedString *attributedImage = [NSAttributedString attributedStringWithAttachment:(NSTextAttachment *)(textAttachment)];
//图片插入到文字后方
[scaleStr appendAttributedString:attributedImage];
//如果要插入到前面
// [scaleStr insertAttributedString:attributedImage atIndex:0];
return scaleStr;
}
2.使用YYText库,这个扩展性更好,如果做直播的话,可以用在聊天窗口,可以添加UIKit的控件,可以添加事件
- (YYTextLayout *)createTextImage:(NSString*)text witImage:(NSString*)imageName withSize:(CGSize)finalSize{
UIFont *font = [UIFont systemFontOfSize:14];
NSMutableAttributedString *textGold = [[NSMutableAttributedString alloc] initWithString:text attributes:@{NSForegroundColorAttributeName:[UIColor blackColor], NSFontAttributeName:font}];
//可以添加UIKit的控件及事件
UIImageView *imagImage = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 50, 50)];
NSMutableAttributedString *attachTextRecahrage = [NSMutableAttributedString yy_attachmentStringWithContent:imagImage contentMode:UIViewContentModeLeft attachmentSize:CGSizeMake(62, 22) alignToFont:font alignment:YYTextVerticalAlignmentCenter];
[textGold appendAttributedString:attachTextRecahrage];
//如果要插入到前面
// [textGold insertAttributedString:attachTextRecahrage atIndex:0];
YYTextContainer *container = [YYTextContainer containerWithSize:CGSizeMake(finalSize.width, finalSize.height)]; //图文混排需要的宽度及高度
YYTextLayout *textLayout = [YYTextLayout layoutWithContainer:container text:textGold];
return textLayout;
}
//使用
YYLabel *labeShow = [[YYLabel alloc] initWithFrame:CGRectMake(0, 0,100, 50)];
labeShow.textColor = [UIColor blackColor];
labeShow.textLayout = [self createTextImage:@"文字" witImage:@"图片" withSize:labeShow.size];
labeShow.textAlignment = NSTextAlignmentLeft;
[self.view addSubview:labeShow];