简体   繁体   中英

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

in my codes:

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];

the struct 'rect' does not correct, why?

I have found an answer and it is working properly for me. I am using a NSMutableAttributedString with text and attachments.

I have created a category of NSMutableAttributedString and add a method as follows:

- (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;
}

Hope this will help someone.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM