开发中有时候会遇到需要图文混排的情况,简单记录下,方便以后copy😁
oc版本,这里是对NSString进行了扩展 @interface NSString (Extension)
@end
@implementation NSString (Extension)
/// 实现图文混排的方法
/// @param array 内容数组(字符/图片)
/// @param font 字体
/// @param color 字体颜色
/// @param imgSize 图片大小
+ (NSAttributedString *) hzj_getAttriString:(NSArray *) array font:(UIFont *)font color:(UIColor*)color imgSize:(CGSize)imgSize{
NSMutableAttributedString *mutableAttr = [[NSMutableAttributedString alloc] init];
for (id obj in array) {
if ([obj isKindOfClass:[NSString class]]) {//字符类型
NSAttributedString *textAttr = [[NSMutableAttributedString alloc] initWithString:(NSString *)obj attributes:@{NSFontAttributeName:font,NSForegroundColorAttributeName:color}];
[mutableAttr appendAttributedString:textAttr];
}else if ([obj isKindOfClass:[UIImage class]]) {//图片类型
NSTextAttachment *attachment = [[NSTextAttachment alloc] init];
attachment.image = (UIImage *)obj;
//使图片上下居中
CGFloat paddingTop = (font.lineHeight - font.pointSize) + (imgSize.height - font.lineHeight) / 2;
attachment.bounds = CGRectMake(0, -paddingTop, imgSize.width, imgSize.height);
[mutableAttr appendAttributedString:[NSAttributedString attributedStringWithAttachment:attachment]];
}
}
return mutableAttr;
}
@end
swift版 extension String {
/// 实现图文混排的方法
/// - Parameters:
/// - array: 图文数组
/// - font: 字体
/// - color: 字体颜色
/// - imgSize: 图片大小
/// - Returns:
static func hzj_getAttriString(_ array:[Any?], font:UIFont ,color:UIColor, imgSize:CGSize) -> NSAttributedString{
let mutableAttr = NSMutableAttributedString()
for item in array {
if let obj = item as? String{//字符类型
let textAttr = NSAttributedString(string: obj, attributes: [NSAttributedString.Key.font : font, NSAttributedString.Key.foregroundColor:color])
mutableAttr.append(textAttr)
}else if let obj = item as? UIImage {//图片类型
let attachment = NSTextAttachment()
attachment.image = obj
//使图片上下居中
let paddingTop = (font.lineHeight - font.pointSize) + (imgSize.height - font.lineHeight) / 2
attachment.bounds = CGRect(x: 0, y: -paddingTop, width: imgSize.width, height: imgSize.height)
mutableAttr.append(NSAttributedString(attachment: attachment))
}
}
return mutableAttr
}
}
使用的方法
- (void)test {
NSAttributedString *attri = [NSString hzj_getAttriString:@[@"文本1",[UIImage imageNamed:@"图片"],@"文本2"] font:[UIFont systemFontOfSize:12] color:[UIColor redColor] imgSize:CGSizeMake(20, 20)];
}
func test() {
let attri = String.hzj_getAttriString(["文本1","可以使用空格作为间距",nil,UIImage(named: "图片"),"只会处理文本/图片类型",nil], font: .customFont(ofSize: 12), color: .red, imgSize: CGSize(width: 20, height: 20))
}