原因:在 NSAttributedString 加入图片后,发现图片默认是与文字底部对齐的,但很多情况下,我们都希望图片与文字垂直居中对齐。
解决:NSAttributedString 并没有提供垂直对齐的属性,但可以通过 Baseline 的方式解决。
代码如下:
float textHeight = size.height/4;
float fontSize = 20.0f;
CGRect rect = CGRectMake(0.0f, 0.0f, size.width, size.height);
#pragma mark 生成富文本
// 文字
NSMutableAttributedString *attrStr = [[NSMutableAttributedString alloc]initWithString:textString];
// 文字图片居中(核心:设置基线)
[attrStr addAttribute: NSBaselineOffsetAttributeName value:@((textHeight-fontSize)/2) range: NSMakeRange(0,attrStr.length)];
// 图片
NSTextAttachment * attach = [[NSTextAttachment alloc] init];
attach.image = [UIImage imageNamed:imageName];
attach.bounds = CGRectMake(0, 0, textHeight, textHeight);
NSAttributedString * imageStr = [NSAttributedString attributedStringWithAttachment:attach];
[attrStr insertAttributedString:imageStr atIndex:0];
// 设置统一的属性
[attrStr addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"HelveticaNeue-Bold"size:fontSize] range:NSMakeRange(0, attrStr.length)];
[attrStr addAttribute:NSForegroundColorAttributeName value:[UIColor grayColor] range:NSMakeRange(0, attrStr.length)];
NSMutableParagraphStyle *paragraph = [[NSMutableParagraphStyle alloc]init];
paragraph.alignment = NSTextAlignmentCenter;
[attrStr addAttribute:NSParagraphStyleAttributeName value:paragraph range:NSMakeRange(0, attrStr.length)];
参考自