Dynamic row height for NSTableView in Swift/Cocoa

柔情痞子 提交于 2019-12-04 15:33:58
ArtbyKGH

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)

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