我想在一个ViewController上有多个NSTableViews.我用以下代码实现了第一个TableView:
class MainViewController: NSViewController
{
@IBOutlet weak var tableView: NSTableView!
override func viewDidLoad()
{
super.viewDidLoad()
let nib = NSNib(nibNamed: "MyCellView", bundle: NSBundle.mainBundle())
tableView.registerNib(nib!, forIdentifier: "MyCellView")
let appDelegate = NSApplication.sharedApplication().delegate as! AppDelegate
appDelegate.view = self
}
}
extension MainViewController: NSTableViewDataSource, NSTableViewDelegate
{
func numberOfRowsInTableView(tableView: NSTableView) -> Int
{
return 5
}
func tableView(tableView: NSTableView, heightOfRow row: Int) -> CGFloat
{
return 25
}
func tableView(tableView: NSTableView, viewForTableColumn tableColumn: NSTableColumn?, row: Int) -> NSView?
{
let cell = tableView.makeViewWithIdentifier("MyCellView", owner: self) as! MyCellView
cell.itemName.stringValue = "row text"
return cell
}
}
Run Code Online (Sandbox Code Playgroud)
这个NSTableView工作正常,但它显然与视图控制器紧密相关.添加第二个NSTableView的最佳方法是什么?
终于找到了如何做到这一点.在我看来,这比将NSTableView放在主控制器中要好得多.
每个表都有自己的类:
import Cocoa
class Table1: NSTableView, NSTableViewDataSource, NSTableViewDelegate
{
override func drawRect(dirtyRect: NSRect)
{
super.drawRect(dirtyRect)
}
func numberOfRowsInTableView(tableView: NSTableView) -> Int
{
return 10
}
func tableView(tableView: NSTableView, heightOfRow row: Int) -> CGFloat
{
return 50
}
func tableView(tableView: NSTableView, viewForTableColumn tableColumn: NSTableColumn?, row: Int) -> NSView?
{
let cell = tableView.makeViewWithIdentifier("MyCellView", owner: self) as! MyCellView!
cell.itemName.stringValue = "hello"
cell.itemDescription.stringValue = "This is some more text"
return cell
}
}
Run Code Online (Sandbox Code Playgroud)
表2是相同的,但显然可以有不同的数据等.
我的表是基于视图的,所以这里是单元视图类定义:
import Cocoa
class MyCellView: NSTableCellView
{
@IBOutlet weak var itemName: NSTextField!
@IBOutlet weak var itemDescription: NSTextField!
}
Run Code Online (Sandbox Code Playgroud)
这是View Controller方法:
import Cocoa
class ViewController: NSViewController
{
var dataSource1 : Table1!
var dataSource2 : Table2!
@IBOutlet weak var table1: NSTableView!
@IBOutlet weak var table2: NSTableView!
override func viewDidLoad()
{
super.viewDidLoad()
self.dataSource1 = Table1()
table1.setDataSource(self.dataSource1)
table1.setDelegate(self.dataSource1)
self.dataSource2 = Table2()
table2.setDataSource(self.dataSource2)
table2.setDelegate(self.dataSource2)
let nib = NSNib(nibNamed: "MyCellView", bundle: NSBundle.mainBundle())
table1.registerNib(nib!, forIdentifier: "MyCellView")
table2.registerNib(nib!, forIdentifier: "MyCellView")
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1165 次 |
| 最近记录: |