([NSAttributedString boundingRectWithSize: options: context:]) method cannot get the correct size in 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 string 'rect' is incorrect, why?

+6
source share
1 answer

I found the answer and it works correctly for me. I am using NSMutableAttributedString with text and attachments.

I created the NSMutableAttributedString category and add the following method:

 - (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 helps someone.

0
source

Source: https://habr.com/ru/post/973894/


All Articles