How to check if UILabel is truncated?

前端 未结 20 2748
不知归路
不知归路 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:24

    Here's the selected answer in Swift 3 (as an extension). The OP was asking about 1 line labels. Many of the swift answers I tried here are specific to multi-line labels and aren't flagging correctly on single line labels.

    extension UILabel {
        var isTruncated: Bool {
            guard let labelText = text as? NSString else {
                return false
            }
            let size = labelText.size(attributes: [NSFontAttributeName: font])
            return size.width > self.bounds.width
        }
    }
    

提交回复
热议问题