macOS - 如何在 NSTableView 中使用复选框?
macOS - How do I use checkbox in NSTableView?
我正在尝试将复选框添加到基于视图的 tableView 的第一列。我拖了一个复选框按钮到列,然后结构就像
Table View
First Column
Check
Check
Text Cell
然后在我正在做的视图控制器的tableView
方法中
if identifier == "Check" {
let cell = tableView.makeView(withIdentifier: NSUserInterfaceItemIdentifier(rawValue: "Check"), owner: self) as! NSTableCellView
return cell
}
我收到 运行 时间错误 Could not cast value of type 'NSButton' to 'NSTableCellView'
,正确的做法是什么?
NSTableCellView
有一个 imageView
和一个 textField
出口。您需要一个复选框,您可以添加一个。 Subclass NSTableCellView
并添加一个 outlet 'checkBox'。在 IB 中,更改单元格视图的 class,将文本字段替换为复选框(或添加复选框)并连接 'checkBox' 插座。在 tableView(_:viewFor:row:)
中,使用 checkBox
而不是 textField
。
很简单。
在基于 NSTableView
的视图中,您可以使用从 NSView
继承的任何视图作为 table 单元格视图。默认是带有文本字段的 NSTableCellView
,但也可以使用 NSTextField
或 NSButton
等控制对象,而无需 任何底层自定义视图,只需拖动即可他们进入 table 视图 canvas.
发生错误是因为您必须将创建的视图转换为正确的类型。如果您使用的是复选框,则将视图投射到 NSButton
.
不要考虑 cell,考虑 view。我什至建议将变量命名为 view
而不是 cell
.
NSUserInterfaceItemIdentifier
扩展是定义常量的推荐模式
extension NSUserInterfaceItemIdentifier {
static let check = NSUserInterfaceItemIdentifier(rawValue: "Check")
}
let view = tableView.makeView(withIdentifier: .check, owner: self) as! NSButton
我正在尝试将复选框添加到基于视图的 tableView 的第一列。我拖了一个复选框按钮到列,然后结构就像
Table View
First Column
Check
Check
Text Cell
然后在我正在做的视图控制器的tableView
方法中
if identifier == "Check" {
let cell = tableView.makeView(withIdentifier: NSUserInterfaceItemIdentifier(rawValue: "Check"), owner: self) as! NSTableCellView
return cell
}
我收到 运行 时间错误 Could not cast value of type 'NSButton' to 'NSTableCellView'
,正确的做法是什么?
NSTableCellView
有一个 imageView
和一个 textField
出口。您需要一个复选框,您可以添加一个。 Subclass NSTableCellView
并添加一个 outlet 'checkBox'。在 IB 中,更改单元格视图的 class,将文本字段替换为复选框(或添加复选框)并连接 'checkBox' 插座。在 tableView(_:viewFor:row:)
中,使用 checkBox
而不是 textField
。
很简单。
在基于 NSTableView
的视图中,您可以使用从 NSView
继承的任何视图作为 table 单元格视图。默认是带有文本字段的 NSTableCellView
,但也可以使用 NSTextField
或 NSButton
等控制对象,而无需 任何底层自定义视图,只需拖动即可他们进入 table 视图 canvas.
发生错误是因为您必须将创建的视图转换为正确的类型。如果您使用的是复选框,则将视图投射到 NSButton
.
不要考虑 cell,考虑 view。我什至建议将变量命名为 view
而不是 cell
.
NSUserInterfaceItemIdentifier
扩展是定义常量的推荐模式
extension NSUserInterfaceItemIdentifier {
static let check = NSUserInterfaceItemIdentifier(rawValue: "Check")
}
let view = tableView.makeView(withIdentifier: .check, owner: self) as! NSButton