I’m new to programming for the iPhone and i’m wondering: how extensible are the various controls? Let’s take the button as an example:
- can i change the background graphic?
- can i make it grow larger when i press on it?
- can i change the font?
- can i use a custom font?
- can i use a button graphic in place of text?
In general, yes to all your questions. You can subclass the various UI* classes that make up the Cocoa touch controls just like any other classes, and add your own custom functionality in the appropriate methods. The only tricky part is figuring out where exactly your code should go.
Let’s look at your UIButton example, and walk through what you want to do with it.
Background image
The UIButton class already has a method
setBackgroundImage:forState:that lets you change the UIImage the button displays when it’s in one of several states, such as Normal, Highlighted, Disabled, and so on.For example, to change the image the button displays as a normal background to “backgroundImage.png”, which is an image file in your application’s bundle:
Growing larger
You can change the button’s
frame(an inherited property from UIView) by adding a method to do so in the view controller .m file that manages the button, then adding that method as an action for a control event on the button.Let’s say you want to double the size of the button. In
viewDidLoad:or somewhere similar, add the following code:Then create a method
growButtonwith the following code:This doubles your button’s size while keeping its center the same. (Be careful your button doesn’t grow over the edge of your view when you do this.)
Changing the font
Simply change the
fontproperty of the UIButton – set it to a new instance of UIFont, like in this example:This changes the button’s font to the system’s font with size 16.
Custom font
This is a somewhat trickier question, as I’m pretty sure you can’t load your own custom font files, even if you include them in your app bundle. You can, however, change the default font of a control by using UIFont’s
fontWithName:size:class method. All the font names are available through UIFont’sfamilyNamesandfontNamesForFamilyName:methods.Button graphics instead of text
This is the simplest of the five – just don’t set the text on the button, but instead set a background image for
UIControlStateNormal(see above).