Multiline UILabel with adjustsFontSizeToFitWidth

前端 未结 8 1499
北海茫月
北海茫月 2020-12-04 12:16

I have a multiline UILabel whose font size I\'d like to adjust depending on the text length. The whole text should fit into the label\'s frame without truncating it.

8条回答
  •  温柔的废话
    2020-12-04 13:01

    Thought I would add my own take on the answer:

    I think it's a slight improvement on some of the other answers because:

    1. Caching while looping through words to find the longest by width, to prevent unnecessary calculations
    2. All the label attributes are used when doing size calculations

    https://gist.github.com/chrisjrex/c571056a4b621f7099bcbd5e179f184f

    Note: This solution should only be used when a UILabel has .numberOfLines = 0 and .lineBreakMode = .byWordWrapping

    Otherwise you are better off using: .adjustFontSizeForWidth = true from the standard swift library

    The other answers on this thread were very helpful to me in coming up with my solution, thank you

提交回复
热议问题