jjzjj

ios - ([NSAttributedString boundingRectWithSize :options:context:])method can not get the right size within NSTextAttachment

coder 2023-09-23 原文

在我的代码中:

NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:@"12123"];
NSTextAttachment *attachment = [[NSTextAttachment alloc] init];
attachment.image = [UIImage imageNamed:@"002"];
attachment.bounds = CGRectMake(0, 0, 20, 20);

[str insertAttributedString:[NSAttributedString attributedStringWithAttachment:attachment] atIndex:2];
CGRect rect = [str boundingRectWithSize:CGSizeMake(200, CGFLOAT_MAX)
                                options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading
                                context:nil];

struct 'rect' 不正确,为什么?

最佳答案

我找到了一个答案,它对我来说工作正常。我正在使用带有文本和附件的 NSMutableAttributedString。

我创建了一个NSMutableAttributedString类,并添加了如下方法:

- (CGSize)getCoveredSizeForMaxSize:(CGSize)maxSize numberOfLines:(NSInteger)lines
{
    UILabel* dummyLabel = [UILabel new];
    [dummyLabel setFrame:CGRectMake(0, 0, maxSize.width, CGFLOAT_MAX)];
    dummyLabel.numberOfLines = lines;
    [dummyLabel setLineBreakMode:NSLineBreakByWordWrapping];
    dummyLabel.attributedText = self;
    [dummyLabel sizeToFit];

    return dummyLabel.frame.size;
}

希望这会对某人有所帮助。

关于ios - ([NSAttributedString boundingRectWithSize :options:context:])method can not get the right size within NSTextAttachment,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25339814/

有关ios - ([NSAttributedString boundingRectWithSize :options:context:])method can not get the right size within NSTextAttachment的更多相关文章

随机推荐