What's the best way to set the x,y coordinate of UILabel but let it auto width/height on the iPhone?

StackOverflow https://stackoverflow.com/questions/929014

  •  06-09-2019
  •  | 
  •  

Question

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.

No correct solution

OTHER TIPS

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);

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top