iOS为什么设置NSBaselineOffsetAttributeName时NSTextAttachment会消失? [英] iOS Why do NSTextAttachment disappear when setting NSBaselineOffsetAttributeName?

查看:2890
本文介绍了iOS为什么设置NSBaselineOffsetAttributeName时NSTextAttachment会消失?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想对齐NSTextAttachment到文本的中心,所以我设置
NSBaselineOffsetAttributeName来改变NSTextAttachment的基线。

I want to align the NSTextAttachment to the center of the text, so I set NSBaselineOffsetAttributeName to change the baseline of NSTextAttachment.

NSMutableAttributedString *attrString = [[NSMutableAttributedString alloc] initWithString:@"" attributes:@{NSFontAttributeName: [UIFont fontWithName:@"STHeitiSC-Light" size:17]}];
NSTextAttachment *attachment = [[NSTextAttachment alloc] init];
attachment.image = [UIImage imageNamed:@"micon"];        
NSMutableAttributedString *ats = [[NSAttributedString attributedStringWithAttachment:attachment] mutableCopy];
[ats addAttributes:@{NSBaselineOffsetAttributeName:@(-5),NSFontAttributeName: [UIFont fontWithName:@"STHeitiSC-Light" size:17]} range:(NSRange){0,ats.length}];
[attrString appendAttributedString:s];

然后我计算UILabel的大小并设置attributedText。

Then I calculate the size for UILabel and set attributedText.

CGRect textFrame = [attrString boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading context:nil];
UILabel *label = [[UILabel alloc] initWithFrame:textFrame];
label.lineBreakMode = NSLineBreakByCharWrapping;
label.numberOfLines = 0;
label.attributedText = attributed;
label.backgroundColor = [UIColor clearColor];

最后一张图片消失了。

任何人都可以解释为什么会这样,如何修复它。

Can anyone explain why this is happening and how to fix it.

推荐答案

我最后通过添加另一个属性来解决它 NSParagraphStyleAttributeName

I finally solve it by adding another attribute NSParagraphStyleAttributeName

    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    paragraphStyle.minimumLineHeight = lineheight; //line height equals to image height
    [attributes setValue:paragraphStyle forKey:NSParagraphStyleAttributeName];

不要改变图像的偏移量,只需设置文本的偏移量。

don't change the image's offset, just set the text's offset.

这篇关于iOS为什么设置NSBaselineOffsetAttributeName时NSTextAttachment会消失?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆