Showing posts with label sizeThatFits. Show all posts
Showing posts with label sizeThatFits. Show all posts

Monday, October 11, 2010

How to Find Out Width of Truncated UILabel Text

Found out my tip "How to Float an Icon after UILabel" worked only in positive scenarios. If your text string is longer than UILabel width, icon could have been pushed out of sight. In worst case nobody would ever have seen the icon!
// Title
label = (UILabel *)[cell viewWithTag:1];
label.text = @"This is a very long title which is too long";

// Icon
image = (UIImageView *)[cell viewWithTag:10];
image.image = [UIImage imageNamed:@"logo.png"];
Some measurements of different methods, just to check what is available:
CGSize frame1 = label.frame;
// 205x21
CGSize frame2 = [label sizeThatFits:label.frame.size];
// 291x19
CGSize frame3 = [label.text sizeWithFont:label.font constrainedToSize:label.frame.size];
// 163x19
CGSize frame4 = [label.text sizeWithFont:label.font constrainedToSize:label.frame.size lineBreakMode:label.lineBreakMode];
// 203x19
CGSize frame5 = [label.text sizeWithFont:label.font forWidth:label.frame.size.width lineBreakMode:label.lineBreakMode];
// 203x19
Next icon positioning. Here you should have calculations to compensate for different icon sizes (in case all of your icons are not same size):
// Icon positioning
CGSize frame = image.frame;
frame.origin.x = label.frame.origin.x + frame5.width + 4;
image.frame = frame;
Ok, now that's perfect (until next defect report)!

Wednesday, October 6, 2010

How to Float an Icon after UILabel

Want to place a floating icon right after a variable lenght text string - using Interface Builder? Wonderful helper that IB tool or so I thought...

First create a UITableViewCell template with IB, put there a fixed lenght UILabel followed by a UIImageView. No problems, their values are easy to setup at cellForRowAtIndexPath with view tag id numbers:
UILabel *label = nil;
UIImageView *image = nil;
CGRect frame;

// Title
label = (UILabel *)[cell viewWithTag:1];
label.text = @"Title text";
But how to "float" that image right after text string? UILabel is fixed sized, so that won't help. Have to check the size of label.text instead:
// Icon
image = (UIImageView *)[cell viewWithTag:10];
image.image = [UIImage imageNamed:@"logo.png"];

// Icon positioning
frame = image.frame;
CGSize f = [label sizeThatFits:label.frame.size];
frame.origin.x = label.frame.origin.x + f.width + 4;
image.frame = frame;
That's it, very simple! Just beware that your tag numbers MUST be unique.

I had a problem that Interface Builder wanted to set UITableViewCell tag same as my image tag. No errors, no warnings, no indications of problem - except that I couldn't get my image frame no matter how much I banged head into brickwall! Removing tag didn't help, it just automagically came back. Ouch!