How to tell when a UILabel will be truncated an/or its line break position will change

后端 未结 5 1342
栀梦
栀梦 2021-01-13 01:38

I have a multi-line UILabel (numberOfLines = 0). It\'s width can change at runtime, and sometimes this leads to truncation and/or re-wrapping. Some

5条回答
  •  醉酒成梦
    2021-01-13 02:33

    Swift 3 solution

    You can count the number of lines after assigning the string and compare to the max number of lines of the label.

    import Foundation
    import UIKit
    
    extension UILabel {
    
        func countLabelLines() -> Int {
            // Call self.layoutIfNeeded() if your view is uses auto layout
            let myText = self.text! as NSString
            let attributes = [NSFontAttributeName : self.font]
    
            let labelSize = myText.boundingRect(with: CGSize(width: self.bounds.width, height: CGFloat.greatestFiniteMagnitude), options: NSStringDrawingOptions.usesLineFragmentOrigin, attributes: attributes, context: nil)
            return Int(ceil(CGFloat(labelSize.height) / self.font.lineHeight))
        }
    
        func isTruncated() -> Bool {
    
            if (self.countLabelLines() > self.numberOfLines) {
                return true
            }
            return false
        }
    }
    

提交回复
热议问题