在 iOS 项目中我会做类似的事情:
tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 30
并且可以很好地调整单元格的大小。
我应该怎么做才能在 macOS 项目中重现相同的行为?
好的,func tableView(_ tableView: NSTableView, heightOfRow row: Int) -> CGFloat
。
我是否应该配置我的 SubView(单元格 View )(实际上是 NSView)两次...
在这两种方法中 - heightOfRow
和 viewFor tableColumn
?
我听说过 cell 的重用,但是没有 nibs 能做到吗?
无论如何,如果我这样做,我不会得到预期的结果。
委托(delegate)/数据源:
let items = ["second label",
"second label with alotoftext alotof...", // long line
"second label"]
func numberOfRows(in tableView: NSTableView) -> Int {
return 3
}
func tableView(_ tableView: NSTableView, heightOfRow row: Int) -> CGFloat {
let cell = SubView(text: items[row])
cell.layoutSubtreeIfNeeded()
return cell.frame.size.height
}
func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? {
return SubView(text: items[row])
}
subview :
init(text: String) {
super.init(frame: CGRect.zero)
let text1 = NSTextField(labelWithString: "first label")
let text2 = NSTextField(labelWithString: text)
text2.lineBreakMode = .byWordWrapping
text2.setContentCompressionResistancePriority(100, for: .horizontal)
self.addSubview(text1)
self.addSubview(text2)
text1 <- [Top(5), Left(5), Right(5)]
text2 <- [Top(0).to(text1, .bottom), Left(5), Right(5), Bottom(5)]
}
最后两行是EasyPeasy约束条件。
我的错误在哪里?
还有一个问题:我应该怎么做才能使单元格垂直增长/减少以适应其中的所有 subview ,从而相应地调整 tableView 的宽度?
哦,好像意识到了。
刚刚添加了观察者:
name: NSNotification.Name.NSViewFrameDidChange,
object: self.scrollView
和
let vr = scrollView.contentView.visibleRect
let indexes = tableView.rows(in: vr).toRange()!
tableView.noteHeightOfRows(withIndexesChanged: IndexSet(integersIn: indexes))
在选择器方法中。
是的。相同的 View ( subview )在没有 tableView 的情况下也能完美工作。
但我仍然遇到上述错误大小的 cellView 问题。
P.S.:对不起我的英语,我希望一切都清楚。
最佳答案
在 macOS 上它有点困难,但并不难做到。
NSTableView
的作者 corbin dunn 对此有一个很好的回答 here .
简而言之:
您需要知道单元格的大小并在
func tableView(NSTableView, heightOfRow: Int)
这是 NSTableViewDelegate
的一个方法。
2016 年 11 月更新:
你快到了!您创建的 View 没有设置宽度。所以我猜测 View 本身假定它比 tableView 窄得多,因此更高。
func tableView(_ tableView: NSTableView, heightOfRow row: Int) -> CGFloat {
let cell = SubView(text: items[row])
cell.frame.size.width = tableView.frame.size.width
cell.layoutSubtreeIfNeeded()
return cell.frame.size.height
}
我没有测试过这段代码,但应该是这样。
关于swift - 我应该使用什么替代 UITableViewAutomaticDimension 来在 NSTableView 中获得相同的效果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40688353/