简体   繁体   English

NSString包含表情符号时如何获得NSString大小?

[英]How to get NSString size when NSString includes emojis?

I am currently using 我目前正在使用

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

to get the size of an NSString. 获得NSString的大小。 However, when that string includes emojis, it seems to calculate the size for the literal unicode character rather than taking into account the size of the emoji itself, rendering the returned size incorrect. 但是,当该字符串包含表情符号时,它似乎计算文字unicode字符的大小,而不是考虑表情符号本身的大小,使得返回的大小不正确。

How do I correctly get the size of the string with emoji characters, as it will appear in a uilabel? 如何使用表情符号正确获取字符串的大小,因为它将显示在uilabel中?

The NSString is not presenting the emoji, it's representing a string, so the sizeWithFont will only account for the string. NSString没有呈现表情符号,它表示一个字符串,因此sizeWithFont只会考虑字符串。

I would use: 我会用:

CGRect labelFrame = label.frame;  
labelFrame.size = [label sizeThatFits:CGSizeMake(100, 9999)];  
[label setFrame:labelFrame]; 

or 要么

//Alternatively  
[label sizeToFit];

Bare in mind that sizeToFit calls the sizeThatFits: method, so in terms of just setting the label to the right height, sizeThatFits: is quicker, and much easier on the eye. 请记住, sizeToFit调用sizeThatFits:方法,因此只需将标签设置为正确的高度,sizeThatFits:更快,更容易在眼睛上。

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. 我通过创建带有文本的NSAttributed String来解决这个问题,然后使用NSAttributedString方法boundingRectWithSize:options:context:来获取字符串的大小。

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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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