ios NSTextAttachment无法将基线偏移量设置为零

时间:2018-11-06 02:53:37

标签: ios nsattributedstring

NSMutableAttributedString *attrString = ({

    // words
    NSAttributedString *leftString = [[NSAttributedString alloc] initWithString:@"好" attributes:@{NSFontAttributeName: [UIFont systemFontOfSize:10]}];

    // image
    NSAttributedString *attachString = ({
        UIImage *image = [UIImage imageNamed:@"项目标签"];
        NSTextAttachment *attach = [NSTextAttachment new];
        attach.image = image;

        [NSAttributedString attributedStringWithAttachment:attach];
    });

    NSMutableAttributedString *attrString = [[NSMutableAttributedString alloc] initWithAttributedString:leftString];
    [attrString appendAttributedString:attachString];

    // set line-height
    NSMutableParagraphStyle *style = [NSMutableParagraphStyle new];
    style.maximumLineHeight = 22.5;
    style.minimumLineHeight = 22.5;

    [attrString addAttribute:NSParagraphStyleAttributeName value:style range:NSMakeRange(0, attrString.length)];

    // set baselineOffset
    [attrString addAttribute:NSBaselineOffsetAttributeName value:@0 range:NSMakeRange(0, attrString.length)];

    attrString;
});

如果图像附件之前有一些单词,则图像的attributedString的基线偏移量不能设置为0。

here is the demo project

here is the screenshot

1 个答案:

答案 0 :(得分:0)

我自己解决了。

只需将NSTextAttachment的bound.origin.y设置为字体的后代。