0

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).

SuddenMoustache
  • 883
  • 7
  • 17

1 Answers1

0

This seems to work:

    let width = self.textField.bounds.width
    let cell = (self.textField.cell() as? NSCell)!
    let rect = cell.drawingRectForBounds(NSMakeRect(CGFloat(0.0), CGFloat(0.0), width, CGFloat(CGFloat.max)))
    let size = cell.cellSizeForBounds(rect)
    self.textField.setFrameSize(NSMakeSize(width, size.height))

Similar problem with a different solution: NSTextFieldCell's cellSizeForBounds: doesn't match wrapping behavior?

Community
  • 1
  • 1
Willeke
  • 14,578
  • 4
  • 19
  • 47
  • It's *so* very nearly correct but sometimes off. I've no idea why that would be... – SuddenMoustache Oct 03 '16 at 21:25
  • Yes, I noticed that. When resizing my window, sometimes the last word 'i' doesn't fit. Recalculating later fixes it. It feels like the cell isn't ready yet. – Willeke Oct 03 '16 at 22:16
  • The 'i' isn't working correctly when my text field is being edited. – Willeke Oct 03 '16 at 23:24
  • Yes, recalculating later does fix it. Gah. No idea what to do here. I think it's just impossible to accurately calculate the height of a wrapping NSTextField in a tableView's heightForRow. Perhaps I should switch to NSTextView... – SuddenMoustache Oct 04 '16 at 09:43