Saturday, July 26, 2008

Dynamic Table View

Here is a simple kind of editable Table View. The NSTableView itself (actually, the NSTableColumn) does not have editing enabled. Instead, we provide a text box and a + button to allow editing. We check to see if a row is selected, and add the new text after that row.



I've put the code for the Controller in a separate class. The class is instantiated with a blue cube in the nib and outlets and actions are wired up in the usual way. (Don't forget to import it in the App Delegate file). Here is the code:


class MyTVController(NSObject):
tv = objc.IBOutlet()
tf = objc.IBOutlet()
addButton = objc.IBOutlet()
deleteButton = objc.IBOutlet()

def awakeFromNib(self):
self.L = ['John','Paul','George','Ringo']
self.tv.setDelegate_(self)
self.tv.setDataSource_(self)
self.tv.reloadData()

@objc.IBAction
def add_(self,sender):
value = self.tf.stringValue()
NSLog("add_ %s" % value)
i = self.tv.selectedRow()
if i == -1: self.L.append(value)
else: self.L.insert(i+1,value)
self.tv.reloadData()

@objc.IBAction
def delete_(self,sender):
NSLog("delete_")

def numberOfRowsInTableView_(self,tv):
return len(self.L)

def tableView_objectValueForTableColumn_row_(
self,tv,tc,r):
return self.L[r]

No comments: