Swift/Cocoa中NSTableView的动态行高 [英] Dynamic row height for NSTableView in Swift/Cocoa

查看:135
本文介绍了Swift/Cocoa中NSTableView的动态行高的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

链接答复未回答问题.我仍然坚持下去...

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.

如果我在IB中为尺寸样式打勾自动",这将使所有行的高度都很小.看起来iOS拥有UITableViewAutomaticDimension,它可以自动缩放表格,但我找不到NSTableView那样的东西.

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 // ????
}

并且我可以使用它来设置行高(上面的设置将我所有行的高度设置为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?

推荐答案

这是一个解决方案

首先,您需要在代码中设置一个NSTextfield.这是一个虚拟"字段,因为它从未真正绘制过

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

然后在heightOfRow函数中

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
}

更多详细信息和NSTextfield扩展可以找到

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)

这篇关于Swift/Cocoa中NSTableView的动态行高的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆