iOS开发中经常需要在富文本(NSAttributedString)中添加图片(NSTextAttachment)。那么如何添加图片呢?代码如下
UIFont *font = [UIFont systemFontOfSize:12];
NSDictionary<NSAttributedStringKey,id> *attributes = @{
NSFontAttributeName: font,
};
//生成富文本
NSMutableAttributedString *attributedText = [[NSMutableAttributedString alloc] initWithString:@"我忘记了" attributes:attributes];
//添加图片
[attributedText appendAttributedString:({
NSTextAttachment *attachment = [[NSTextAttachment alloc] init];
UIImage *image = [UIImage imageNamed:@"icon"];
attachment.image = image;
attachment.bounds = CGRectMake(0, 0, image.size.width, image.size.height);
[NSAttributedString attributedStringWithAttachment:attachment];
})];
代码写好了,编译运行,看看效果:
这肯定不是设计师需要的效果,如何让文字和图片在竖直方向上居中对齐呢?其实很简单,修改
attachment.bounds.origin.y
即可:
UIFont *font = [UIFont systemFontOfSize:12];
NSDictionary<NSAttributedStringKey,id> *attributes = @{
NSFontAttributeName: font,
};
//生成富文本
NSMutableAttributedString *attributedText = [[NSMutableAttributedString alloc] initWithString:@"我忘记了" attributes:attributes];
//添加图片
[attributedText appendAttributedString:({
NSTextAttachment *attachment = [[NSTextAttachment alloc] init];
UIImage *image = [UIImage imageNamed:@"icon"];
attachment.image = image;
attachment.bounds = CGRectMake(0, -4.5, image.size.width, image.size.height);
[NSAttributedString attributedStringWithAttachment:attachment];
})];
设置好attachment.bounds.origin.y
了,再重新编译运行看看效果:
效果不错,达到了设计师需要的效果。那么问题来了,为何要设置
attachment.bounds.origin.y = -4.5
呢?我试了十遍试出来的
每次新添加或者切换字体都试上十遍,肯定不是我们想要的,那有没有更好的方式呢?答案肯定是有的,设置
attachment.bounds.origin.y = round(font.capHeight - image.size.height)/2.0
即可:
UIFont *font = [UIFont systemFontOfSize:12];
NSDictionary<NSAttributedStringKey,id> *attributes = @{
NSFontAttributeName: font,
};
//生成富文本
NSMutableAttributedString *attributedText = [[NSMutableAttributedString alloc] initWithString:@"我忘记了" attributes:attributes];
//添加图片
[attributedText appendAttributedString:({
NSTextAttachment *attachment = [[NSTextAttachment alloc] init];
UIImage *image = [UIImage imageNamed:@"icon"];
attachment.image = image;
attachment.bounds = CGRectMake(0, round(font.capHeight - image.size.height)/2.0, image.size.width, image.size.height);
[NSAttributedString attributedStringWithAttachment:attachment];
})];
再次编译运行得到我们想要的效果:
参考:https://stackoverflow.com/questions/26105803/center-nstextattachment-image-next-to-single-line-uilabel
关于bound的设置可参考:https://www.jianshu.com/p/964313cfbdaa