Dynamic row height for NSTableView in Swift/Cocoa

2019-04-14 17:28发布

EDIT: The question was not answered by the linked reply. I'm still stuck on this...

I've got a table that I use for chat messages. Each message is a variably-sized box including some text. I want the row height in my table to dynamically change depending on the size of the message box.

If I tick 'automatic' for size style in IB, it makes all of the rows have tiny heights. It looks like iOS have UITableViewAutomaticDimension which automatically scales the table, but I can't find anything like that for NSTableView.

I know there's an option to create the following function:

func tableView(_ tableView: NSTableView, heightOfRow row: Int) -> CGFloat
{
       return 50 // ????
}

and I am able to set the row height using that (the above sets all of my rows to height 50), but I don't know how to make it dependent on the size of the text in my box. How can I do this efficiently?

1条回答
祖国的老花朵
2楼-- · 2019-04-14 18:03

Here's one solution

First you set up a NSTextfield in code. This is a "virtual" field in as it is never actually drawn

    var fakefield = NSTextField()  
// Set the fontsize etc to be what you will use in the table

Then in the heightOfRow function

func tableView(tableView: NSTableView, heightOfRow row: Int) -> CGFloat {

    let item = yourArray[row] 
    let fakefield.stringValue = item 
    // exactly how you get the text out of your data array depends on how you set it up

    let yourHeight = fakefield.cell!.cellSizeForBounds(NSMakeRect(CGFloat(0.0), CGFloat(0.0), yourWidth, CGFloat(FLT_MAX))).height
    // yourWidth = the width of your cell as CGFloat.  

    return yourHeight
}

more details and NSTextfield extensions can be found Here. Note this answer is in Swift 2.3 (haven't made the plunge to 3 yet)

查看更多
登录 后发表回答