How to check if UILabel is truncated?

前端 未结 20 2757
不知归路
不知归路 2020-11-28 02:53

I have a UILabel that can be varying lengths depending on whether or not my app is running in portrait or landscape mode on an iPhone or iPad. When the text is

20条回答
  •  心在旅途
    2020-11-28 03:16

    I had issues with boundingRect(with:options:attributes:context:) when using autolayout (to set a max height) and an attributed text with NSParagraph.lineSpacing

    The spacing between lines was ignored (even when passed in attributes to the boundingRect method) so the label might be considered as not truncated when it was.

    The solution I found is to use UIView.sizeThatFits :

    extension UILabel {
        var isTruncated: Bool {
            layoutIfNeeded()
            let heightThatFits = sizeThatFits(bounds.size).height
            return heightThatFits > bounds.size.height
        }
    }
    

提交回复
热议问题