ios android 图文混排,IOS中的图文混排

开发中有时候会遇到需要图文混排的情况,简单记录下,方便以后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))

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值