How to adjust and make the width of a UILabel to fit the text size?

后端 未结 8 2225
被撕碎了的回忆
被撕碎了的回忆 2020-12-13 06:01

In my project, there is a UILabel with text. The font size is 16pt. The text contents are changed depending on different cases. I hope it can automatically adju

相关标签:
8条回答
  • 2020-12-13 06:39

    Using Auto Layout:

    In the ViewController:

    override func viewDidLoad() {
        super.viewDidLoad()
    
        sampleLabel.text = "Electrical Maintenance and Repair"
        sampleLabel.sizeToFit()
    }
    
    0 讨论(0)
  • 2020-12-13 06:41

    Follow this.

    CGSize stringsize = [yourString sizeWithFont:[UIFont systemFontOfSize:fontSize]]; 
    [label setFrame:CGRectMake(x,y,stringsize.width,height)];
    [label setText: yourString];
    
    0 讨论(0)
提交回复
热议问题