views:

670

answers:

2

I know exactly where I want to position my UILabel in a UIView, but I don't necessarily know what height/width I want it to have at compile time, so setting a width/height in initWithFrame is useless. I want to be able to just init its x,y point, and then use something like [myLabel sizeToFit] so it can automagically set the width/height based on my break mode and content.

The solution I'm looking for is how to set the UILabel's point of origin while setting it's width/height to a dynamic number based on the text set to the label.

+2  A: 

If you already have the frame with dynamic size but want to change the origin:

CGRect myFrame = myLabel.frame;
myFrame.origin = aCGPoint;
myLabel.frame = myFrame;

If you need to calculate the size:

CGSize suggestedSize = [myString sizeWithFont:myLabel.font constrainedToSize:CGSizeMake(FLT_MAX, FLT_MAX) lineBreakMode:UILineBreakModeWordWrap];

Of course, you can change the FLT_MAX to constrain to a specific width or heigh.

EDIT: I didn't realize you wanted to programatically calculate the size. Added a better explanation above.

Kenneth Ballenegger
This doesn't answer the question of how to set the height/width to a dynamic size which changes at runtime based on textual input.
Coocoo4Cocoa
See my edit above.
Kenneth Ballenegger
+1  A: 

Size the label first, then set its origin or center:

[myLabel sizeToFit];
CGRect frame = myLabel.frame;
frame.origin = CGPointMake(x, y);
myLabel.frame = frame;

or

[myLabel sizeToFit];
myLabel.center = CGPointMake(x, y);
Daniel Dickison