【发布时间】:2018-04-30 00:43:01
【问题描述】:
我正在使用 XCode 9.3,Swift 为 MacOS 开发应用程序。
我创建了一个当前有两列的表。我想使用只作用于一列的类型选择,这样当用户键入前几个字母时,它只在第一列中选择,而不是在第二列中选择。
Apple 文档在 Objective-C 中有一个示例:https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/TableView/RowSelection/RowSelection.html#//apple_ref/doc/uid/10000026i-CH6-SW1 但我似乎无法将其翻译成 Swift。我在下面包含了表格代码。任何帮助都将不胜感激。
extension ViewController: NSTableViewDataSource {
func numberOfRows(in tableView: NSTableView) -> Int {
return directoryItems?.count ?? 0
}
// Sorting.
func tableView(_ tableView: NSTableView, sortDescriptorsDidChange oldDescriptors: [NSSortDescriptor]) {
guard let sortDescriptor = tableView.sortDescriptors.first else {
return
}
if let order = Directory.FileOrder(rawValue: sortDescriptor.key!) {
sortOrder = order
sortAscending = sortDescriptor.ascending
reloadFileList()
}
}
}
extension ViewController: NSTableViewDelegate {
fileprivate enum CellIdentifiers {
static let NameCell = "NameCellID"
static let TimeCell = "TimeCellID"
static let SizeCell = "SizeCellID"
}
func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? {
var image: NSImage?
var text: String = ""
var cellIdentifier: String = ""
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = .long
dateFormatter.timeStyle = .long
guard let item = directoryItems?[row] else {
return nil
}
if tableColumn == tableView.tableColumns[0] {
image = item.icon
text = item.name
cellIdentifier = CellIdentifiers.NameCell
} else if tableColumn == tableView.tableColumns[1] {
let asset = AVAsset(url: item.url as URL)
let audioTime = asset.duration
text = audioTime.durationText
cellIdentifier = CellIdentifiers.TimeCell
} else if tableColumn == tableView.tableColumns[2] {
text = item.isFolder ? "--" : sizeFormatter.string(fromByteCount: item.size)
cellIdentifier = CellIdentifiers.SizeCell
}
if let cell = tableView.makeView(withIdentifier: NSUserInterfaceItemIdentifier(rawValue: cellIdentifier), owner: nil) as? NSTableCellView {
cell.textField?.stringValue = text
cell.imageView?.image = image ?? nil
return cell
}
return nil
}
}
【问题讨论】:
-
到目前为止您尝试了哪些方法,结果与您想要的有何不同?
-
我已经尝试过:
func tableView(_ tableView: NSTableView,shouldTypeSelectFor event: NSEvent,withCurrentSearch searchString: String?) -> Bool { return true }如果我将返回更改为 false,则类型选择在任何地方都不起作用。我尝试添加 if 语句,但似乎无法提取列或单元格的名称。他们都回来“零”。我不完全确定我是否在正确的地方尝试了该功能,或者它是否是正确的开始。我可以用它来捕获可选的搜索字符串,但仅此而已。 -
您能否发布您尝试获取列名的
shouldTypeSelectFor:etc:etc:方法的内容?我可能可以帮助解决这个问题,但我需要看看你到目前为止所做的尝试,看看出了什么问题。 -
我试过把它放在 NSTableViewDelegate;
func tableView(_ tableView: NSTableView,shouldTypeSelectFor event: NSEvent,withCurrentSearch searchString: String?) -> Bool { if tableView.cell?.title == "NameCellID" { print(String(describing: tableView.cell?.title)) return true } else { print(String(describing: tableView.cell?.title)) return false } }tableView.cell?.title 只是显示为 nil。我希望我对此有更好的理解,但我就是没有。
标签: swift macos nstableview