*Accurately* calculating text height in Cocoa (for Mac, not iOS)

前端 未结 6 1238
一向
一向 2020-12-14 04:32

How can I calculate the height of a string within a particular label (NSTextField), for some given fixed width?

I Googled up various methods and tried this method fr

6条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-14 05:04

    This is ArtbyKGH's answer for Swift 4+:

    extension NSTextField {
        func bestHeight(for text: String, width: CGFloat) -> CGFloat {
            stringValue = text
            let height = cell!.cellSize(forBounds: NSRect(x: 0, y: 0, width: width, height: .greatestFiniteMagnitude)).height
    
            return height
        }
    
        func bestWidth(for text: String, height: CGFloat) -> CGFloat {
            stringValue = text
            let width = cell!.cellSize(forBounds: NSRect(x: 0, y: 0, width: .greatestFiniteMagnitude, height: height)).width
    
            return width
        }
    }
    

提交回复
热议问题