How to get NSString size when NSString includes emojis?

后端 未结 2 1856
醉话见心
醉话见心 2021-01-17 16:30

I am currently using

- (CGSize)sizeWithFont:(UIFont *)font constrainedToSize:(CGSize)size lineBreakMode:(UILineBreakMode)lineBreakMode

to

2条回答
  •  温柔的废话
    2021-01-17 17:29

    I struggled with this same thing for a while, attempting multiple solutions including the accepted answer, which did not work for me. I solved this by creating an NSAttributed String with the text, then using the NSAttributedString method boundingRectWithSize:options:context: to get the size of the string.

    NSString *text = //some text
    CGFloat maxSize = //text size constraints
    
    NSAttributedString *attributedString = [[NSAttributedString alloc] initWithString:text
                                                                           attributes:@{NSFontAttributeName : font
                                                                                        }];
    
    CGRect boundingRect = [attributedString boundingRectWithSize:maxSize options:NSStringDrawingUsesLineFragmentOrigin context:nil];
    CGSize fitSize = boundingRect.size;
    

提交回复
热议问题