I am getting the text size of a string with this
textSize = [[tempDict valueForKeyPath:@"caption.text"] sizeWithFont:[UIFont systemFontOfSize:12] constrainedToSize:CGSizeMake(280, CGFLOAT_MAX) lineBreakMode: NSLineBreakByWordWrapping];
The only problem I have is that if the string only contains an emoji, my app crashes. Is there an easy way to check for emojis or do I have to create an array with all possible emojis and then check for them using that?
error:
-[NSNull sizeWithFont:constrainedToSize:lineBreakMode:]: unrecognized selector sent to instance 0x3aa88a60
if ([tempDict valueForKeyPath:@"caption.text"]){
NSLog(@"%@", [tempDict valueForKeyPath:@"caption"]);
//Measure the message label box height
textSize = [[tempDict valueForKeyPath:@"caption.text"] sizeWithFont:[UIFont systemFontOfSize:12] constrainedToSize:CGSizeMake(280, CGFLOAT_MAX) lineBreakMode: NSLineBreakByWordWrapping];
int height = 320 + 20 + textSize.height;
[cellHeight addObject:[NSNumber numberWithInt:height]];
}
Again and again people use valueForKeyPath instead of objectForKey. None of them can ever explain why. Read the documentation. If after reading it you can explain why you are using valueForKeyPath (and "I copied it from somewhere" is not an explanation), change it to objectForKey.
The problem you have has nothing to do with Emojis at all. Any attempt to detect Emojis in the string will fail - for the simple reason that you don't have a string in the first place, you have [NSNull null]. The problem might be fixed by using objectForKey - you might get nil instead which behaves a lot more forgiving. Or you still get [NSNull null].
Find out why you are getting [NSNull null]. Somebody puts it there. If you can't prevent it from being there, then you need to handle it.
Please, see this answer How to get NSString size when NSString includes emojis?
If you have only emojis then you shouldn't use
sizeWithFont
. Use label for it or something else.NSString doesn't work with Emojis, only text. If you have emojis, then you should use
[label sizeToFit]
or[label sizeThatFits:]
Also, you can use this code:
Because, you get NSNull from dictionary, but it doesn't equal nil, and your condition works.
Now with the new release of iOS 10, for the following emojis it doesn't work:
Emojis
The following code snippet is tried and tested for both iOS 9 and iOS 10:
Create a String extension in your app as mentioned above.
And can be used like this:
try this code:
As you've probably noticed, all of these emoji detecting methods break almost anytime Apple adds new emojis.
I've created a CG scanning solution which should work for all current and all FUTURE emojis here: https://stackoverflow.com/a/14472163/2057171
To my knowledge it's the only actual answer to this issue posted anywhere online.
You can use it like so:
This is what I'm using:
I took this which was missing some emoji ranges, and then used this emoji array to find missing rantes by iteration... Have not deep tested.