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

前端 未结 6 1236
一向
一向 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 04:47

    Thanks indeed to iphaaw and Enchilada for this really cool little solution. I found it worked so well at setting row heights etc that I converted iphaaw's Swift into a couple of NSTextField extensions. Enjoy

    extension NSTextField {
    func bestheight(text: String, width: CGFloat) -> CGFloat {
    
        self.stringValue = text
        let getnumber = self.cell!.cellSizeForBounds(NSMakeRect(CGFloat(0.0), CGFloat(0.0), width, CGFloat(FLT_MAX))).height
    
        return getnumber
       }
    }
    
    extension NSTextField {
    func bestwidth(text: String, height: CGFloat) -> CGFloat {
    
        self.stringValue = text
        let getnumber = self.cell!.cellSizeForBounds(NSMakeRect(CGFloat(0.0), CGFloat(0.0), CGFloat(FLT_MAX), height)).width
    
        return getnumber
       }
    }
    

    I hope someone finds these helpful. regards KGH

提交回复
热议问题