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

后端 未结 5 2709
眼角桃花
眼角桃花 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:34

    This will work..

    • Set minimum scale factor for your label. as shown in this image.
    • Set number of lines = 2 // or zero (0) if you want more number of lines
    • Set line breaking mode to '.byTruncatingTail' for 2 lines

    Swift 3
    Set number of lines zero for dynamic text information, it will be useful for varying text.

    var label = UILabel()
    let stringValue = "A label\nwith\nmultiline text."
    label.text = stringValue
    label.numberOfLines = 2 // 0
    label.lineBreakMode = .byTruncatingTail // or .byWrappingWord
    label.minimumScaleFactor = 0.5 // It is not required but nice to have a minimum scale factor to fit text into label frame
    

    enter image description here

    Also, don't set height constraint for your label more than 2 lines.

提交回复
热议问题