Four
Four

Reputation: 506

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. 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.

How do I correctly get the size of the string with emoji characters, as it will appear in a uilabel?

Upvotes: 10

Views: 4594

Answers (3)

Raman
Raman

Reputation: 211

This solution works for me. With it you can calculate string size without UILabel creation.

let maxWidth = 350.0
let string = "String👌"
let attributedString = NSAttributedString(string: string)
let framesetter = CTFramesetterCreateWithAttributedString(stringToSize)
let size = CTFramesetterSuggestFrameSizeWithConstraints(framesetter, CFRange(location: 0, length: self.string.unicodeScalars.count), nil, CGSize(width: maxWidth, height: CGFloat.infinity), nil)

Upvotes: 0

lramirez135
lramirez135

Reputation: 3062

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;

Upvotes: 1

user352891
user352891

Reputation: 1191

The NSString is not presenting the emoji, it's representing a string, so the sizeWithFont will only account for the string.

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.

Upvotes: 2

Related Questions