views:

363

answers:

1

I'm trying to put a text badge on my Iphone app with the undocumented setApplicationBadgeString method. The problem I'm having is getting the number of characters right. Sometimes I can fit characters, sometimes it replaces part of my string with dots. I've seen the same behaviour on UILabel too, if the text doesn't fit, it gets cut off by "...". How can I programmatically find out when the text will get truncated in the specific case of the text badge, as I have no way to check its size - it actually appears not to be constant. Thank you!

+1  A: 

The number of charachters varies because the width of the characters varies. a W is longer than an *l**, so a bunch of W's will be truncated sooner than a bunch of l's.

Through trial and error you could use NSString's method - (CGSize)sizeWithFont:(UIFont *)font to find out the maximum width allowed on a badge. You will have to figure out what font size the badge uses though. Your code would should end up looking something like this...

// I'm not sure what the badge font size is, you will have to test for this
UIFont *font = [UIFont systemFontOfSize:12];

// Keep adding 1's to the badge string until you get the ...'s, then you will 
// know the maximum size of the badge string!
NSString *badgeString = @"111";  
NSLog(@"width: %f", [badgeString sizeWithFont:font].width);

[[UIApplication sharedApplication] setApplicationIconBadgeNumber:badgeString];
probablyCorey