How much room does that text take up in your UILabel?

Today I wanted to create a graphical border around the text in a UILabel… kind of like a notification badge. However, it had to be completely dynamic based upon the area the string would consume in the UI… notably the width. In Flash there are some hacks to roll this kind of functionality (autoresize, etc.) In Objective-C, it’s a lot easier to do.

In my project I have UILabel above a UIImageView in the display order. The UIImageView is set up with a stretchable image:

UIImage *img = [[UIImage imageNamed:@"stretchImage.png"]
    stretchableImageWithLeftCapWidth:4.0 topCapHeight:4.0];
myImageView.image = img;

I have this in my viewDidLoad. Your stretchable caps may vary as needed. So now with that set up, I have a method I use to set the string into the label which will affect the UIImageView:

- (void) setSectionLabel:(NSString *)title {
    sectionLabel.text = title;
    CGSize expectedLabelSize = [title sizeWithFont:sectionLabel.font
        constrainedToSize:CGSizeMake(526.0,22.0)
        lineBreakMode:sectionLLabel.lineBreakMode];
    float w = (float)expectedLabelSize.width + 15;
    myImageView.frame = CGRectMake(20,8,w,22.0);
}

The 526 and 21 come from how I originally positioned the UIImageView (width and height). In the frame code, the 20 and 8 come from the x and y initial positioning – this keeps it in place. So you can see that width is being generated from the expectedLabelSize & I add some padding to it. The UIImageView is stretched behind the text perfectly, the image within bound by the stretchable rules set up.

Related Posts Plugin for WordPress, Blogger...

Leave a Reply

Your email address will not be published. Required fields are marked *


+ five = 14

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>