How to adjust a label size to fit the length of the text

前端 未结 8 745
无人及你
无人及你 2020-12-20 12:27

I have searched the solution to this in the past QAs, but could not find the right one.
Does anyone know how to adjust aUILabel size dynamically to fit the

8条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-20 12:37

    Xcode 8 and iOS 10

    This is quite easy to do with Auto Layout. No need to do anything in code.

    Use Auto Layout

    Use auto layout to pin each label's top and left edges only. Don't add constraints for the width and height. The view's intrinsic content size will take care of that.

    Here is what the constraints look like:

    Code

    There is nothing at all special about the code. No need to use sizeToFit or anything like that.

    import UIKit
    class ViewController: UIViewController {
    
        @IBOutlet weak var labelOne: UILabel!
        @IBOutlet weak var labelTwo: UILabel!
        @IBOutlet weak var labelThree: UILabel!
    
        @IBAction func changeTextButtonTapped(_ sender: UIButton) {
    
            labelOne.text = "David"
            labelTwo.text = "met"
            labelThree.text = "her"
        }
    }
    

    Notes

    • This answer has been retested with Xcode 8, iOS 10, and Swift 3.
    • See my other answer if you want multi-line resizing.
    • Thanks to this answer for setting me on the right track.

提交回复
热议问题