Reputation: 30035
Is there any method to determine how much of an NSString can be rendered in a given space?
I know about all the NSString sizeWithFont methods (e.g. sizeWithFont:constrainedToSize:lineBreakMode:). If the string is too long to fit though, these don't tell you what portion of the string was able to be rendered.
For example, if I have
NSString *testString = @"The brown dog";
And I call:
[testString sizeWithFont:[UIFont systemFontOfSize:17] constrainedtoSize:CGSizeMake(20, 20) lineBreakMode:UILineBreakModeWordWrap];
I may get back a CGSize = {20,20}. That tells me the string took at least the entire size, but it doesn't tell me if it was over, or how much was able to fit. If only "The brown" was able to fit, I'd like to know that.
Maybe some Core Foundation methods to do this?
Upvotes: 3
Views: 347
Reputation: 17898
One way to tell if it's going to truncate is to provide a very large height in the constrain rect. If the height that comes back is taller than the height of your label, you know it would be truncated. Something like this:
// myLabel is a UILabel*
CGSize labelSize = myLabel.frame.size;
labelSize.height = 9999;
CGSize newSize = [newLabel sizeWithFont:[UIFont systemFontOfSize:17.0]
constrainedToSize:labelSize
lineBreakMode:UILineBreakModeWordWrap];
if( newSize.height > labelSize.height ) {
// Whoops, too big!
}
That will tell you if it would be truncated, but it won't tell you how much of it would be. Only way I can think to do that would be to do this in a loop, removing a word off the end each time until it fits.
Upvotes: 1