Xcode - Swift - UILabel width extension for text

I want the height of the UILabel to expand depending on its text.

Here's what the view controller looks like, with the label selected:

enter image description here

Here is the code (I tried a bunch of different similar things, but this is what I have now):

import UIKit class ViewControllerTEST: UIViewController { @IBOutlet weak var label: UILabel! override func viewDidLoad() { super.viewDidLoad() label.frame = CGRectMake(0, 0, CGRectGetWidth(label.bounds), 0) label.numberOfLines = 0 label.lineBreakMode = .ByWordWrapping label.text = "This is a really\nlong string" label.setNeedsLayout() label.sizeToFit() label.frame = CGRectMake(0, 0, CGRectGetWidth(label.bounds), CGRectGetHeight(label.bounds)) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ } 

And, as you can see here, this does not work as intended:

enter image description here

+4
source share
1 answer

Do not use a frame, use autorun. Add the top, leading, and end anchors to the label (I would suggest doing this in a storyboard). As long as your lines is 0 (what you are doing), the height will automatically change. If you want to add restrictions to the code, your viewDidLoad will look something like this:

 override func viewDidLoad() { super.viewDidLoad() label.text = "This is a really\nlong string" label.setTranslatesAutoresizingMaskIntoConstraints(false) view.addSubview(label) let views = ["label": label] view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-[label]-|", options: nil, metrics: nil, views: views)) view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-[label]", options: nil, metrics: nil, views: views)) } 
+6
source

All Articles