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.
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.