IB – User Defined Runtime Attributes

Working on my MIDIChimes application, adding a piano-type keyboard UI, I happened to notice a section in the Interface Builder Identity Inspector I’d always glossed over before — the “User Defined Runtime Attributes” section (I’m going to abbreviate as ‘UDRA’s from here on out). The XCode Help for this is actually pretty good. I’d recommend skimming through it.

Before I get into the details of UDRAs , I need to describe the piano keyboard UI. I added lots of NSButtons of style ‘Square’. These buttons don’t have to be square; I don’t know why the IB calls them that. Anyway, there’s one button for every piano key, laid out like you would expect:


However, these buttons are actually PianoKey subclasses of NSButton:

class PianoKey: NSButton {
    override func drawRect(dirtyRect: NSRect) {
		if isBlack {
			let color = NSColor(deviceRed:0.8, 

	func midiNote(transposeNote: MIDI_Note?) -> MIDI_Note? {
		let transposeVal = transposeNote?.rawValue ?? 0
		let n = note.unsignedCharValue
		let o = octave.unsignedCharValue
		let rawValue = n + o * 12 + transposeVal
		return MIDI_Note(rawValue: rawValue)
	dynamic var note: NSNumber = 0
	dynamic var octave: NSNumber = 0
	dynamic var isBlack = false

Those 3 properties of PianoKey can all be set using the UDRA UI in Interface Builder:


Each key is assigned a unique pair . Note is from 0 to 11. Octave is from 0 to 2 in my example, since there are 3 octaves on the keyboard.

Note that the isBlack property is used in the drawRect method to draw the black keys darker. (I played around with the color values until I was happy with the compromises between ‘off’ and ‘on’ black key contrast.)

I’m not really sure how much time this technique saved me. It might have been better to make the piano keyboard one big control and figure out which key is getting clicked mathematically. I doubt it, but maybe.

Leave a Reply

Your email address will not be published. Required fields are marked *