swift 缓存行高,Swift / Cocoa中NSTableView的动态行高

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?

解决方案

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)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值