I need to accurately calculate the size of an NSTextField (because I need that value to calculate the height of the NSTableView's row in which the NSTextField sits). I have a rough approximation now, but it seems off (and I don't want to hard-code fudge it...).
My approximation involves creating a temporary cell, adding the appropriate text to it, and then calculating the height based on that text:
func tableView(_ tableView: NSTableView, heightOfRow row: Int) -> CGFloat
{
let textDistanceFromTableEdge = 192
if let cell = tableView.make(withIdentifier: "IncomingMessage", owner: nil) as? IncomingMessage
{
cell.message.stringValue = messages[row].message
let width = ((tableView.tableColumns.last?.width)! - textDistanceFromTableEdge)
let height = (cell.message.cell!.cellSize(forBounds: NSMakeRect(CGFloat(0.0), CGFloat(0.0), width, CGFloat(FLT_MAX))).height)
return (height + 50)
}
}
This very often gets the right results, but it's just slightly off (often, when a single word wraps to the next line, it will not result in the cell being one line taller).