Tag Archives: NSView

How to add a background image to an NSView

Unlike UIView, NSView does not have a background property – which makes it less obvious how to set either a colour or a background image to your bland grey windows.

Here’s how to do it:

First, create a subclass of NSView and assign it to the view you’d like to change in interface builder. When you create your class Xcode provides two methods for you, one of which is drawRect:dirtyRect. In it you can specify a colour and fill the view with it before calling super:

Now instead of a bland grey you’ll have a shining white.

If a solid colour isn’t what you’re after, create your own colorWithPatternImage and use that instead – therefore adding a background image to your NSView:

How to handle mouse events in OS X

Handling mouse events in OS X is very different from the way in which we’re used to dealing with touch events in iOS. Here’s how to do it:

You must subclass an NSView and assign your class in the the xib file – much like you would subclass a UIViewController and assign your own in the storyboard. Every Cocoa Application has at least one view, found under the Window of your app (you may have to expand the Document Outline for this to show, it’s at the bottom left in Interface Builder):

Screen Shot 2014-04-16 at 08.16.19

Then in your own class you can track mouse events by implementing these functions among several others:

The Apple documentation also mentions that we should override the following method for our custom view to accept mouse events – but in OS X 10.9.2 I didn’t find this to make a difference:

First Mouse Event

There is something called the “first mouse” event. This is called when an app or window not currently in focus is clicked on. Usually that window will ignore where you clicked and only bring the app or window into focus, and then reacts to mouse events.

You can change this behaviour by overriding the following method: