Saturday, July 26, 2008

Cocoa Bindings - NSImage


Here is an example of bindings using an NSImageView. The window of our app contains an NSImageView and a button labeled "switch." The left screenshot is upon loading, the middle is after clicking the button once, and then the right after clicking again.

The button is connected to an action of the same name in the AppDelegate. In the Bindings Inspector, we set the NSImageView's binding for Value to be the AppDelegate with a Model Key Path of "img."

Here is the code for the AppDelegate. We first load two images that have been added to the project under Resources (I grabbed them from Wikipedia). The button's action does what it says.

class PyBind2AppDelegate(NSObject):
img = objc.ivar("img")

def init(self):
self = super(PyBind2AppDelegate, self).init()
self.image1 = NSImage.imageNamed_("bush")
self.image2 = NSImage.imageNamed_("chimp")
return self

def awakeFromNib(self):
self.img = self.image1
NSLog("%s" % self.img.name())

@objc.IBAction
def switch_(self,sender):
if self.img.name() == 'bush':
self.img = self.image2
else:
self.img = self.image1

And here is a similar example where we have a text field and a slider, both of which have a binding of Value to the AppDelegate with a Model Key Path of 'x.' The slider's binding also has update value continuously selected.

Here is the code:

class PyBind4AppDelegate(NSObject):
x = objc.ivar('x')

def awakeFromNib(self):
self.setX_(50)

def setX_(self,value):
self.x = int(value)