Dynamic row height for NSTableView in Swift/Cocoa

纵饮孤独 提交于 2019-12-06 11:40:32

问题


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:


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)



来源:https://stackoverflow.com/questions/39644212/dynamic-row-height-for-nstableview-in-swift-cocoa

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!