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); //根據(jù)圖片位置進(jìn)行調(diào)整
textAttachment.image = [UIImage imageNamed:imageName];
NSAttributedString *attributedImage = [NSAttributedString attributedStringWithAttachment:(NSTextAttachment *)(textAttachment)];
//圖片插入到文字后方
[scaleStr appendAttributedString:attributedImage];
//如果要插入到前面
// [scaleStr insertAttributedString:attributedImage atIndex:0];
return scaleStr;
}
2.使用YYText庫围详,這個(gè)擴(kuò)展性更好,如果做直播的話,可以用在聊天窗口叭喜,可以添加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];