Publishers of technology books, eBooks, and videos for creative people

Home > Articles

  • Print
  • + Share This
This chapter is from the book


Almost all the drawing functionality you’ve learned about so far also applies to controls. Most controls inherit their class from UIControl, and UIControl is a subclass of UIView circle-a.jpg; this is how controls know how to draw themselves.

You’ll never actually create instances of UIControl directly the way you do with UIView. UIControl is simply used to define a common set of functionality and behavior for its subclasses.

As mentioned at the beginning of this chapter, controls use the target-action mechanism to respond to touch events. Since the iPhone is a Multi-Touch device, many different events can occur, such as tapping, multitapping, dragging, and releasing. Luckily, each control has been designed to respond to only those events appropriate for its usage, and each does so in an intuitive and consistent manner.

You’ll now take a closer look at the controls available to iPhone developers.


When adding buttons to your application, you’ll use the UIButton class circle-b.jpg. The default initializer for buttons is the buttonWithType: method:

UIButton *myButton = [[UIButton buttonWithType: UIButtonTypeRoundedRect];

To be notified when a button changes state, add a target and action:

[myButton addTarget:self action: @selector(buttonClick:) forControlEvents:UIControlEvent TouchUpInside];

The UIControlEventTouchUpInside event is most commonly used for handling regular button presses.

The UIButtonTypeCustom type lets you create buttons with images or even draw them yourself using your own custom drawing code (as discussed earlier in the “Views” section).

To create a button with an image:

  1. Specify an image for the button’s default state using NSControlStateNormal:
    UIImage *buttonImage = [UIImage imageNamed: @"myButtonImage.png"];
    [myButton setImage:buttonImage forState:UIControlStateNormal];

    UIButton will automatically apply highlight effects to indicate that the button is pressed or disabled.

  2. You can also set multiple appearance properties for each of these states, including the title text, font, and color.

    You can use different images for the four different states: the default (as shown in step 1), highlighted, selected, and disabled. This enables you to create buttons to represent other controls.

To create a checkbox button:

  1. Assign images for both of the buttons’ states:
    [checkbox setImage:[UIImage imageNamed:@"checkbox_off.png"] forState:UIControlStateNormal];
    [checkbox setImage:[UIImage imageNamed:@"checkbox_on.png"] forState:UIControlStateSelected];
  2. Set the target method to call when the button is tapped:
    [checkbox addTarget:self action: @selector(checkboxClick:) forControlEvents:UIControlEvent TouchUpInside];
  3. In the checkboxClick: method, simply flip the button’s selected property:
    btn.selected = !btn.selected;

    Since you’ve previously defined images for the two different states, the button automatically updates to display the correct image. Code Listing 4.29 shows the updated code.


Code Listing 4.29 Creating a check box.


Switches, represented by the UISwitch class, let you create an on/off control circle-c.jpg.

To create a switch:

  1. Use the initWithFrame: method:
    CGRect switchRect = CGRectMake (120,50,0,0);
    UISwitch *mySwitch = [[UISwitch alloc] initWithFrame:switchRect];

    Since switches are always the same size, the width and height properties are ignored.

  2. When you change a switch’s value, it generates a UIControlEventValueChanged event:
    [mySwitch addTarget:self action: @selector(switchAction:) forControlEvents:UIControlEvent ValueChanged];
  3. To turn a switch on/off, call the setOn:Animated: method:
    [mySwitch setOn:YES animated:YES];

Switches don’t have any properties for modifying the default visual appearance, but with a little digging, you can control a couple of elements.

Within the control hierarcy of a UISwitch, the “on” and “off” elements are UILabels circle-d.jpg. You can manipulate the text, font, color, and more.

To alter the appearance of a switch:

  1. To retrieve the two UILabels within the switch that hold the switch’s text, you can use this:
    UIView *mainView = [[[[mySwitch subviews] objectAtIndex:0] subviews] objectAtIndex:2];
    UILabel *onLabel = [[mainView subviews] objectAtIndex:0];
    UILabel *offLabel = [[mainView subviews] objectAtIndex:1];
  2. Now you can change the text and color of these labels. The choice of text values is quite limited since the labels are small in size and are clipped by their containing view:
    onLabel.text = @"YES";
    offLabel.text = @"NO";
    onLabel.textColor = [UIColor yellow Color];
    offLabel.textColor = [UIColor green Color];
  3. When setting the text values, you should localize your replacement text wherever possible. Code Listing 4.30 shows the updated code.

Code Listing 4.30 Customizing the switch control.


Although switches have only two possible states, sliders let you select from a range of values on a horizontal bar, or track, with a thumb indicator that can be moved from side to side to select values circle-e.jpg.

Unlike the UISwitch, there’s quite a lot you can do to customize the visual appearance of sliders, such as putting images to represent the values at either end of the track. You can also customize the thumb image and the graphics that appear on the track on both sides of the thumb as the values change circle-f.jpg.

Just as with the UISwitch, sliders create a UIControlEventValueChanged event when their value is changed. By setting the continuous property, you can choose to have these events fired either as the slider is changed or at the end of a change. Code Listing 4.31 demonstrates this with a custom UISlider, with minimum, maximum, and thumb images. In the sliderAction: method, you are forcing a “step” behavior, making the slider jump to the next value in increments of ten. A label added to the view displays the current slider value.


Code Listing 4.31 Implementing a custom slider.

Segmented controls

The UISegmentedControl consists of a horizontal control divided into segments circle-g.jpg. Segmented controls are useful for allowing users to pick from a group or set of values.

Each segment functions as its own button. By default, selecting a segment will deselect the others in the control (much as a radio button does in HTML). You can alter this behavior by setting the momentary property.

To create a segmented control:

  1. Create an array of UIImages or NSStrings, and then call the default initializer initWithItems: (Code Listing 4.32).
  2. Set the frame, and the control will automatically resize to accommodate its segments.

    Each segment will initially be the same size.


    Code Listing 4.32 Creating a segment control.

  3. Set the width of individual segments using the setWidth:forSegmentIndex: method.

    This will automatically resize any other segments that have not had their widths explicitly set to fit within the control.

  4. Select segments using the setSelected SegmentIndex: method.
  5. Disable individual segments using the setEnabled:forSegementAtIndex: method.
  6. Add more segments using insertSegments WithImage:atIndex: animated:


    insertSegmentsWithTitle:atIndex: animated:.

  7. Set the animated property to YES so your segments will “slide in” as they are added.
  8. To remove segments, use the remove SegmentsAtIndex:animated: method.
  9. Use removeAllSegments to clear the entire control.
  • + Share This
  • 🔖 Save To Your Account