Reputation: 11665
I try to add a UILabel by code which works, but not as intended.
With following Code I can see the label but the height of the label is not correct as you can see in the attached screen. I would like the uilabel sized so the height of the label corresponde to the fontsize.
Of course I could simply oversize the UILabels high so the text would fit. But I don't think thats best practice.
How do I size an UILabel based on a fontsize ?
var uilabel1=UILabel();
uilabel1.frame=CGRectMake(0, drawy, screenwidth, ititlesize);
uilabel1.text=sTextViewOptionsTitle;
uilabel1.font = UIFont(name: uilabel1.font.fontName, size: 28);
self.view.addSubview(uilabel1);
var lastelementheigth=uilabel1.frame.height;
UPDATE Solution with sizeToFit()
Thanks for the answer regarding sizeToFit(). This did the trick with some additional code to position the control. updated Code:
var uilabel2=UILabel();
//uilabel2.frame=CGRectMake(0, drawy, screenwidth/2, DropdownHeigth);
uilabel2.text=sTextSizeTextViewer;
uilabel2.font = UIFont(name: uilabel2.font.fontName, size: iFontsize_Option);
uilabel2.sizeToFit();
uilabel2.frame.origin = CGPoint(x: 0, y: drawy);
self.view.addSubview(uilabel2);
lastelementheigth=uilabel2.frame.height;
Upvotes: 1
Views: 704
Reputation: 118761
You may only need to call -sizeToFit
. This will change the label's size to its "preferred" size based on its contents. Then you can reposition the origin or center if desired.
Upvotes: 1
Reputation: 6205
It's been asked before - take a look at: Replacement for deprecated sizeWithFont: in iOS 7?
The method you're looking for is sizeWithAttributes
Upvotes: 0