How do I set adaptive multiline UILabel text? UILable 文本自动换行

 This is much better approach if you are looking for multiline dynamic text label which exactly takes the space based on its text.

No sizeToFit, preferredMaxLayoutWidth used

Below is how it will work.

enter image description here

 Lets set up the project. Take a Single View application and in Storyboard Add a UILabel and a UIButton. Define constraints to UILabel as below snapshot:

enter image description here

Set the Label properties as below image:

enter image description here

Add the constraints to the UIButton. Make sure that vertical spacing of 100 is between UILabel and UIButton

enter image description here

Now set the priority of the trailing constraint of UILabel as 749

enter image description here

Now set the Horizontal Content Hugging and Horizontal Content Compression properties of UILabel as 750 and 748

enter image description here

Below is my controller class. You have to connect UILabel property and Button action from storyboard to viewcontroller class.

import UIKit  class ViewController: UIViewController {  @IBOutlet weak var textLabel: UILabel! var count = 0 let items = ["jackson is not any more in this world", "Jonny jonny yes papa eating sugar no papa", "Ab", "What you do is what will happen to you despite of all measures taken to reverse the phenonmenon of the nature"]   @IBAction func updateLabelText(sender: UIButton) {     if count > 3 {         count = 0     }     textLabel.text = items[count]     count = count + 1 }  override func viewDidLoad() {     super.viewDidLoad()     // Do any additional setup after loading the view, typically from a nib.     //self.textLabel.sizeToFit()     //self.textLabel.preferredMaxLayoutWidth = 500 }  override func didReceiveMemoryWarning() {     super.didReceiveMemoryWarning()     // Dispose of any resources that can be recreated. }   }

Thats it. This will automatically resize the UILabel based on its content and also you can see the UIButton is also adjusted accordingly.

发表回复

您的电子邮箱地址不会被公开。