Advertise Mobile SDKs Books Events Forum News Social Networking Support Us
Follow @iphonedevsdk on Twitter

Interface 2, Advanced iOS
Mockup & Code Gen
($9.99)

Make your own iPhone apps
and run them live!
(free)

Pic Frame Dynamo: Photo Editing
($0.99)

Abiliator
($1.99)

Want your application or service advertised on iPhone Dev SDK?

Go Back   iPhone Dev SDK Forum > iPhone SDK Development Forums > iPhone SDK Development

Reply
 
LinkBack Thread Tools Display Modes
Old 04-20-2011, 06:43 PM   #1 (permalink)
Registered Member
 
Join Date: Apr 2011
Posts: 7
ScottishPirate is on a distinguished road
Default Dynamic UILabel Sizing

Hi All,

I have a very simple app (frankly because I don't know how to create anything more complicated) in which a UILabel, contained within a scroll view, takes on a new string of text when the user touches any 1 of 8 buttons.

My problem is that these strings of text are all of different lengths. I would like to somehow code the UILabel so that it's size is dependent upon the length of text that inhabits it.

I've googled this like crazy, and have found several threads of the same topic, but can't quite seem to get it to work. Could someone please tell me what I need to enter in my .m and .h files in order for this to work properly?

Thank you in advance!
ScottishPirate is offline   Reply With Quote
Old 04-20-2011, 06:56 PM   #2 (permalink)
Reading the Documentation
 
baja_yu's Avatar
 
Join Date: Sep 2010
Location: 45.255019,19.844908
Posts: 5,414
baja_yu has a spectacular aura about
Default

One thing you could use is the sizeWithFont:constrainedToSize:lineBreakMode: method of NSString. You send it to the string you want to put in the label, give it the font and size you will be using in the label, the constraint rect (the size you do not want to go over, for example 300 width and 150 height), and line break mode (word wrap) and it will return you a size of the rectangle in which that text would fit. Based on that you can set the size of the label and calculate the number of lines you need to set.

Now, I'm not sure if there is any easier way, maybe you can dig around the NSString and UILabel class references in the docs and see if you can find something.
baja_yu is offline   Reply With Quote
Old 04-20-2011, 07:03 PM   #3 (permalink)
Cocoa Junkie
 
Duncan C's Avatar
 
Join Date: Dec 2008
Location: Northern Virginia
Posts: 6,003
Duncan C has a spectacular aura about
Default

Quote:
Originally Posted by baja_yu View Post
One thing you could use is the sizeWithFont:constrainedToSize:lineBreakMode: method of NSString. You send it to the string you want to put in the label, give it the font and size you will be using in the label, the constraint rect (the size you do not want to go over, for example 300 width and 150 height), and line break mode (word wrap) and it will return you a size of the rectangle in which that text would fit. Based on that you can set the size of the label and calculate the number of lines you need to set.

Now, I'm not sure if there is any easier way, maybe you can dig around the NSString and UILabel class references in the docs and see if you can find something.

I haven't mucked with this in quite a while. (I'm off working on a Mac OS project.) UIView has a -sizeToFit method. Will a label resize itself if you call that method? You'd need to set the numberOfLines property to 0 first, so the label will use as many lines as needed.

If that doesn't work, baja_yu's method will work. I've used that approach to create custom table view cells that size themselves to the text they are displaying.
__________________
Regards,

Duncan C
WareTo

Check out our apps in the Apple App store


Check out this password generator app that shows various techniques including using a data container singleton object to share data between objects in your project.

See this tutorial on using UIView animations and layer animations:

See this thread on generating random, non-repeating text

Check out a very cool Macintosh Kaleidoscopes app called ScopeWorks that we released to the Mac App store.
Duncan C is offline   Reply With Quote
Old 04-20-2011, 07:04 PM   #4 (permalink)
Registered Member
 
Join Date: Apr 2011
Posts: 7
ScottishPirate is on a distinguished road
Default

So you think I need to manually calculate the size of the frame, based on the string length and font size? There's no good way to create a dynamically sized UILabel?
ScottishPirate is offline   Reply With Quote
Old 04-20-2011, 07:06 PM   #5 (permalink)
Registered Member
 
Join Date: Apr 2011
Posts: 7
ScottishPirate is on a distinguished road
Default

Quote:
Originally Posted by Duncan C View Post
I haven't mucked with this in quite a while. (I'm off working on a Mac OS project.) UIView has a -sizeToFit method. Will a label resize itself if you call that method? You'd need to set the numberOfLines property to 0 first, so the label will use as many lines as needed.

If that doesn't work, baja_yu's method will work. I've used that approach to create custom table view cells that size themselves to the text they are displaying.
I could be wrong (very likely), but I thought sizetofit resized the text to fit the label, and not the label to fit the text.
ScottishPirate is offline   Reply With Quote
Old 04-20-2011, 08:53 PM   #6 (permalink)
Registered Member
 
Join Date: Apr 2011
Posts: 7
ScottishPirate is on a distinguished road
Default

I found a thread that discusses how to vertically align text in a UILabel here:

https://discussions.apple.com/thread...art=0&tstart=0

Does anyone know how to use the .h and .m files that ivan.m has provided?
ScottishPirate is offline   Reply With Quote
Old 04-21-2011, 02:58 AM   #7 (permalink)
Nuisance Developer
 
Join Date: Jul 2009
Location: Italy
Posts: 4,691
dany_dev is on a distinguished road
Default

Quote:
Originally Posted by ScottishPirate View Post
I found a thread that discusses how to vertically align text in a UILabel here:

https://discussions.apple.com/thread...art=0&tstart=0

Does anyone know how to use the .h and .m files that ivan.m has provided?
VerticallyAlignedLabel.h
Code:
//
// VerticallyAlignedLabel.h
//

#import <Foundation/Foundation.h>


typedef enum VerticalAlignment {
 VerticalAlignmentTop,
 VerticalAlignmentMiddle,
 VerticalAlignmentBottom,
} VerticalAlignment;

@interface VerticallyAlignedLabel : UILabel {
@private
 VerticalAlignment verticalAlignment_;
}

@property (nonatomic, assign) VerticalAlignment verticalAlignment;

@end
VerticallyAlignedLabel.m
Code:
//
// VerticallyAlignedLabel.m
//

#import "VerticallyAlignedLabel.h"


@implementation VerticallyAlignedLabel

@synthesize verticalAlignment = verticalAlignment_;

- (id)initWithFrame:(CGRect)frame {
 if (self = [super initWithFrame:frame]) {
 self.verticalAlignment = VerticalAlignmentMiddle;
 }
 return self;
}

- (void)setVerticalAlignment:(VerticalAlignment)verticalAlignment {
 verticalAlignment_ = verticalAlignment;
 [self setNeedsDisplay];
}

- (CGRect)textRectForBounds:(CGRect)bounds limitedToNumberOfLines:(NSInteger)numberOfLines {
 CGRect textRect = [super textRectForBounds:bounds limitedToNumberOfLines:numberOfLines];
 switch (self.verticalAlignment) {
 case VerticalAlignmentTop:
 textRect.origin.y = bounds.origin.y;
 break;
 case VerticalAlignmentBottom:
 textRect.origin.y = bounds.origin.y + bounds.size.height - textRect.size.height;
 break;
 case VerticalAlignmentMiddle:
 // Fall through.
 default:
 textRect.origin.y = bounds.origin.y + (bounds.size.height - textRect.size.height) / 2.0;
 }
 return textRect;
}

-(void)drawTextInRect:(CGRect)requestedRect {
 CGRect actualRect = [self textRectForBounds:requestedRect limitedToNumberOfLines:self.numberOfLines];
 [super drawTextInRect:actualRect];
}

@end
yourDidLoad or everywhere you like in your viewController
Code:
#import VerticallyAlignedLabel.h

....

VerticallyAlignedLabel *myLabel = [[VerticallyAlignedLabel alloc] initWithFrame:CGRectMake(x,y,w,h)];
[myLabel setVerticalAlignment:VerticalAlignmentMiddle]; //change VerticalAlignmentMiddle if you need someother

[self.view addSubview:myLabel];
__________________
dany_dev is offline   Reply With Quote
Old 04-21-2011, 06:23 PM   #8 (permalink)
Registered Member
 
Join Date: Apr 2011
Posts: 7
ScottishPirate is on a distinguished road
Default

So I create a brand new class for the VerticallyAlignedLabel.h and .m, and then call upon that class by importing it into my viewcontroller class?
ScottishPirate is offline   Reply With Quote
Old 04-21-2011, 06:33 PM   #9 (permalink)
Indie Developer
 
iSDK's Avatar
 
Join Date: Jul 2010
Posts: 1,346
iSDK is on a distinguished road
Send a message via AIM to iSDK
Default

I have just successfully done what you wanted in my application.

Here is my code:

Code:
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
Code:
            if (indexPath.row == 3){
                NSString *text = [self getItemForKey:kRights];
                CGSize constraintSize = CGSizeMake(310.0f, MAXFLOAT);
                CGSize labelSize = [text sizeWithFont:[UIFont systemFontOfSize:15]
                                    constrainedToSize:constraintSize 
                                        lineBreakMode:UILineBreakModeWordWrap];
                return labelSize.height+(labelSize.height/2)+([@"Rights" sizeWithFont:[UIFont systemFontOfSize:15]].height);
            }
            else
                return 30;
Code:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
Code:
if (row == 3) {
			cell.textLabel.text = @"Rights";
            cell.backgroundColor = [UIColor clearColor];
            cell.detailTextLabel.lineBreakMode = UILineBreakModeWordWrap;
            cell.detailTextLabel.numberOfLines = 0;
            cell.detailTextLabel.text = [self getItemForKey:kRights];
            cell.textLabel.font = [UIFont systemFontOfSize:15];
            cell.detailTextLabel.font = cell.textLabel.font;
            cell.textLabel.textColor = [UIColor whiteColor];
            CGSize constraintSize = CGSizeMake(310.0f, MAXFLOAT);
            CGSize labelSize = [[cell.detailTextLabel text] sizeWithFont:[cell.detailTextLabel font] constrainedToSize:constraintSize lineBreakMode:UILineBreakModeWordWrap];
            cell.detailTextLabel.frame = CGRectMake( 0, 0, 310, labelSize.height);
            cell.userInteractionEnabled = YES;
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.accessoryType = UITableViewCellAccessoryNone;

		}
Hope it helps
iSDK is offline   Reply With Quote
Old 04-21-2011, 06:54 PM   #10 (permalink)
Registered Member
 
Join Date: Apr 2011
Posts: 7
ScottishPirate is on a distinguished road
Default

So I created a new class for the verticallyalignedlabel, ran it and everything worked well.

Then, I added that last piece of code to my view controller class, in the viewdidload section, and I had a number of errors. First, I had an error with the import, which I corrected by adding "" to your code.

I also have an error saying that x, y, w, and h are undeclared, which makes me think that it isn't importing the verticallyalignedlabel.h properly.

Any thoughts?
ScottishPirate is offline   Reply With Quote
Old 04-21-2011, 06:58 PM   #11 (permalink)
Registered Member
 
Join Date: Apr 2011
Posts: 7
ScottishPirate is on a distinguished road
Default

Quote:
Originally Posted by iSDK View Post
I have just successfully done what you wanted in my application.

Here is my code:

Code:
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
Code:
            if (indexPath.row == 3){
                NSString *text = [self getItemForKey:kRights];
                CGSize constraintSize = CGSizeMake(310.0f, MAXFLOAT);
                CGSize labelSize = [text sizeWithFont:[UIFont systemFontOfSize:15]
                                    constrainedToSize:constraintSize 
                                        lineBreakMode:UILineBreakModeWordWrap];
                return labelSize.height+(labelSize.height/2)+([@"Rights" sizeWithFont:[UIFont systemFontOfSize:15]].height);
            }
            else
                return 30;
Code:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
Code:
if (row == 3) {
			cell.textLabel.text = @"Rights";
            cell.backgroundColor = [UIColor clearColor];
            cell.detailTextLabel.lineBreakMode = UILineBreakModeWordWrap;
            cell.detailTextLabel.numberOfLines = 0;
            cell.detailTextLabel.text = [self getItemForKey:kRights];
            cell.textLabel.font = [UIFont systemFontOfSize:15];
            cell.detailTextLabel.font = cell.textLabel.font;
            cell.textLabel.textColor = [UIColor whiteColor];
            CGSize constraintSize = CGSizeMake(310.0f, MAXFLOAT);
            CGSize labelSize = [[cell.detailTextLabel text] sizeWithFont:[cell.detailTextLabel font] constrainedToSize:constraintSize lineBreakMode:UILineBreakModeWordWrap];
            cell.detailTextLabel.frame = CGRectMake( 0, 0, 310, labelSize.height);
            cell.userInteractionEnabled = YES;
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.accessoryType = UITableViewCellAccessoryNone;

		}
Hope it helps
Thanks for this! Will this still work with my app though? I have the label embedded in a scroll view, on a tab bar view controlled window. Like I said earlier, I'm very new to xcode. What is a table view?
ScottishPirate is offline   Reply With Quote
Old 04-21-2011, 07:04 PM   #12 (permalink)
Indie Developer
 
iSDK's Avatar
 
Join Date: Jul 2010
Posts: 1,346
iSDK is on a distinguished road
Send a message via AIM to iSDK
Default

Sorry, didn't read the OP properly... I assumed you were using a tableView as well.

Quote:
Originally Posted by ScottishPirate View Post
Thanks for this! Will this still work with my app though? I have the label embedded in a scroll view, on a tab bar view controlled window. Like I said earlier, I'm very new to xcode. What is a table view?
iSDK is offline   Reply With Quote
Reply

Bookmarks

Tags
dynamic, sizing, uilabel

Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On



» Advertisements
» Online Users: 346
13 members and 333 guests
dansparrow, dre, iOS.Lover, LezB44, lorrettaui53, Nobbsy, Objective Zero, oztemel, pbart, samdanielblr, sledzeppelin, thephotographer, Trickphotostudios
Most users ever online was 1,387, 04-10-2012 at 04:21 AM.
» Stats
Members: 175,663
Threads: 94,119
Posts: 402,896
Top Poster: BrianSlick (7,990)
Welcome to our newest member, LezB44
Powered by vBadvanced CMPS v3.1.0

All times are GMT -5. The time now is 01:50 AM.
Powered by vBulletin® Version 3.8.0
Copyright ©2000 - 2012, Jelsoft Enterprises Ltd.
Search Engine Friendly URLs by vBSEO 3.3.0