我在IB中创建了一个NSTableView,包含3列(名字、姓氏和电子邮件)。我想添加第四列(年龄)。
let column = NSTableColumn(identifier: NSUserInterfaceItemIdentifier(rawValue: "age"))
column.title = "Age"
column.width = CGFloat(120)
column.minWidth = CGFloat(4)
self.tableView.addTableColumn(column)
这一列已经添加,但内容为空。
我想知道是否存在单元格视图的问题,但不知道如何添加它。有人可以帮忙吗?
谢谢。
以下是完整代码。代码使用Swift 4 Xcode 9编写。
import Cocoa
class Person: NSObject {
var firstName : String
var lastName : String
var emailId : String
var age : Int
init(firstName: String, lastName: String, emailId: String, age: Int){
self.firstName = firstName
self.lastName = lastName
self.emailId = emailId
self.age = age
}
}
class ViewController: NSViewController {
@IBOutlet weak var tableView: NSTableView!
var tableViewData: [Person] = [Person(firstName: "John", lastName: "Apple", emailId: "d.v@stack.com", age: 35),Person(firstName: "Phil", lastName: "Grant", emailId: "dg@yo.com", age: 50),Person(firstName: "lou", lastName: "groth", emailId: "AV@flock.com", age: 14)]
override func viewDidLoad() {
super.viewDidLoad()
let column = NSTableColumn(identifier: NSUserInterfaceItemIdentifier(rawValue: "age"))
column.title = "Age"
column.width = CGFloat(120)
column.minWidth = CGFloat(4)
self.tableView.addTableColumn(column)
self.tableView.delegate = self
self.tableView.dataSource = self
self.tableView.reloadData()
}
}
extension ViewController:NSTableViewDataSource, NSTableViewDelegate{
func numberOfRows(in tableView: NSTableView) -> Int {
return tableViewData.count
}
func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView?{
guard let vw = tableView.makeView(withIdentifier: tableColumn!.identifier, owner: self) as? NSTableCellView else { return nil }
switch tableColumn?.identifier.rawValue {
case "firstName"?:
vw.textField?.stringValue = tableViewData[row].firstName
case "lastName"?:
vw.textField?.stringValue = tableViewData[row].lastName
case "emailId"?:
vw.textField?.stringValue = tableViewData[row].emailId
case "age"?:
vw.textField?.integerValue = tableViewData[row].age
default:
return nil
}
return vw
}
}