Swift 3 - Adjust Font Size to Fit Width, Multiple Lines

后端 未结 5 2707
眼角桃花
眼角桃花 2021-02-20 13:53

I have a UILabel and it is set to 42.0 pt font, and the width of the label is set using autoconstraints based on factors other than the label itself (aka the things to the right

5条回答
  •  我寻月下人不归
    2021-02-20 14:33

    Interesting question. Here's my solution:

    let labelText = self.mylabel.text //where mylabel is the label
    let labelSeperated = self.labelText.components(seperatedBy: " ")
    if labelSeperated.count > 1 {
        myLabel.lineBreakMode = .byWordWrapping
        myLabel.numberOfLines = 0 
    } else {
        myLabel.numberOfLines = 1
        myLabel.adjustsFontSizeToFitWidth = true 
    }
    

    Put this code where the label will be changed. It sets the line number to 0 if there are two or more numbers, otherwise set to 1 line only.

    If you want to resize multi-line labels, check out this blog post.

提交回复
热议问题