原因:在 NSAttributedString 加入圖片后,發(fā)現(xiàn)圖片默認是與文字底部對齊的,但很多情況下,我們都希望圖片與文字垂直居中對齊。
解決: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];
// 設置統(tǒng)一的屬性
[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)];
參考自
最后編輯于 :
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。