Skip to main content

iPhone Custom UIView with Controls

Armed with a copy of the Pragmatic Programmer's book and a lot of Googling, have made a start recently on developing apps for the iPhone. Took a while to find my way around XCode, Interface Builder and to get to thinking again about things like memory management, but made some progress and have released an app for bass guitar players learning scales or modes.

It's fairly straightforward - is based on a navigation controller app, and has a single table view for selecting the scale and then a custom view for displaying the scale itself. You can choose the mode, key and speed and then view the tablature for playing the scale as well as listening to it played and viewing the fingering positions.

The only tricky bit really was the display of the scale and for this I needed to develop a custom UIView. By doing this you can draw directly to the canvas - which I needed to do for the tab lines (or strings) and for plotting the finger positions of the scale. Normally with a view you use Interface Builder or code to generate controls and associate them with IBOutlets and IBActions in XCode. The problem I found was that I wanted to do both - i.e. I needed a custom view in order to display the information that couldn't be rendered using controls, but also wanted to make use of controls for functions like the selection of mode and key.

I also had the issue that I wanted to pass information to the custom UIView, by setting a property for the scale (a custom class I had created which represented the selected scale - with properties like the name, description and intervals).

I solved this using the following code which involves casting the view object to the type of my custom UIView in the UIViewControllers viewWillAppear method, which then allows me to set it's custom property.

- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];

//Pass details of scale in custom property
[(ScaleDisplayView *)[self view] setScale:scale];

//Display scale details
self.nameLabel.text = [NSString stringWithFormat:@"The %@ scale", self.scale.name];
self.descriptionLabel.text = self.scale.description;

//Initialise view
self.title = self.scale.name;
self.view.backgroundColor = [UIColor whiteColor];
[self.view setNeedsDisplay];
}

Comments