ios – NSAttributedString带图像附件和NSTextTab,文本未对齐

前端之家收集整理的这篇文章主要介绍了ios – NSAttributedString带图像附件和NSTextTab,文本未对齐前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我试图在左边有一个带有图像和标题的UIlabel,在右边有一个带有项目符号的描述列表,为此我正在使用NSAttributedString,如下所示:
NSMutableParagraphStyle *pStyle = [[NSMutableParagraphStyle alloc] init];
    pStyle.tabStops =
        @[ [[NSTextTab alloc] initWithTextAlignment:NSTextAlignmentLeft location:tabLocation options:[NSDictionary dictionary]] ];

    NSMutableAttributedString *attString = [[NSMutableAttributedString alloc] init];
    NSTextAttachment *textAttachment = [[NSTextAttachment alloc] init];
    textAttachment.image = [UIImage imageNamed:@"test_image"];
    textAttachment.bounds = CGRectMake(0,-3,15,15);//resize the image
    attString = [NSAttributedString attributedStringWithAttachment:textAttachment].mutableCopy;
    [attString appendAttributedString:[[NSAttributedString alloc]
                                          initWithString:[NSString stringWithFormat:@"title\t\u2022 %@",[@[ @"description1",@"description2" ]
                                                                                        componentsJoinedByString:@"\n\t\u2022 "]]
                                              attributes:@{NSParagraphStyleAttributeName : pStyle}]];
    label.attributedText = attString;

我希望右边的列表保持对齐,但事实并非如此,这是我得到的结果:

我期望列表是这样对齐的:

解决方法

问题在于NSTextTab中的location参数

>根据描述,位置参数有助于从左边距定位文本.所以这就是我们需要的,只需替换下面的行

pStyle.tabStops =  @[ [[NSTextTab alloc] initWithTextAlignment:NSTextAlignmentLeft location:tabLocation options:[NSDictionary dictionary]] ];

pStyle.tabStops = @[[[NSTextTab alloc] initWithTextAlignment:NSTextAlignmentLeft location:[self getTextLocationFor:@"test"]  options:[NSDictionary dictionary]] ];

>添加getTextLocationFor:方法来计算位置,如下所示

-(CGFloat)getTextLocationFor:(NSString *)inputStr{
     CGSize maximuminputStringWidth = CGSizeMake(FLT_MAX,30);
     CGRect textRect = [inputStr boundingRectWithSize:maximuminputStringWidth
                                        options:NSStringDrawingUsesLineFragmentOrigin
                                     attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:15]}
                                        context:nil];
     UIImageView * testImage = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"close_red"]];//Change image name with yours

     return textRect.size.width + testImage.frame.size.width +2;
}

>那就是我们准备好运行你的项目,现在一切都会好的.

结果:

原文链接:https://www.f2er.com/iOS/334440.html

猜你在找的iOS相关文章