Reputation: 11193
I have UILabel in my Cell Subclass which is suppose to hold a title. The size of the title can be various lengths and therefor I need to resize the UILabel to fit the text and to prevent that the text is not to long I also need to be able to set maxHeight. The width should be the same. How can I create such code in swift in a tableViewCell subclass?
So far I have this in awakeFromNib
theTitleLabel?.font = UIFont(name: "HelveticaNeue", size: 13)
theTitleLabel?.textColor = UIColor(rgba: "#4F4E4F")
theTitleLabel?.numberOfLines = 0
theTitleLabel?.lineBreakMode = NSLineBreakMode.ByTruncatingTail
Upvotes: 6
Views: 7721
Reputation: 1
let lblMassage = UILable()
lblMassage.text ="Resizing the height of UILabel to fit text.................."
lblMassage.numberOfLines = 0
lblMassage.lineBreakMode = NSLineBreakMode.byTruncatingTail
lblMassage.preferredMaxLayoutWidth = 190
lblMassage.sizeToFit()
Upvotes: -1
Reputation: 1779
Swift 2 version, from Zigglzworth's answer :
let maximumLabelSize = CGSizeMake(maxWidth, maxHeight);
let expectedSize = theLabel.sizeThatFits(maximumLabelSize)
theLabel.frame = CGRectMake(theLabel.frame.origin.x, theLabel.frame.origin.y, expectedSize.width, expectedSize.height)
Upvotes: 3
Reputation: 130072
The easiest way to do that is using autolayout constraints. You are using awakeFromNib
, so I assume you have that cell somewhere in your Interface Builder (xib or storyboard file).
If you can avoid it, never set up your views in your code. It's far easier to do it in the Interface Builder.
Find your label and set up its attributes (font, color, line break mode etc.) in the Interface Builder.
Add a width constraint (or constraints to left and right margins, depending on what you want).
Add a height constraint, change its relation from = (equals)
to < (less than)
.
You are done, no code is needed.
Upvotes: 4
Reputation: 6803
CGSize maximumLabelSize = CGSizeMake(MAX_WIDTH, MAX_HEIGHT);
CGSize expectedSize = [lbl sizeThatFits:maximumLabelSize];
CGSize s = CGSizeMake(STATIC_WIDTH, expectedSize.height);
yourLabel.frame = CGRectMake(yourLabel.frame.origin.x, nameLbl.frame.origin.y, s.width, s.height);
Upvotes: 6