Segmented Controls Overview

NSSegmentedControl is a subclass of NSControl that implements a horizontal control made of multiple segments. It provides a compact means of grouping together a number of controls, as shown in Figure 1.

Figure 1  A segmented control in Mail
An example of a segmented control

Segments may contain text, images, and menus. One of the simplest applications of a segmented control is its use as a compact alternative to a group of radio buttons. Here, the user makes a single selection from a number of options. In a more complex example, segments can be independently selected or have associated menus.

NSSegmentedControl has these features:

A segmented control’s appearance and behavior are controlled by the class NSSegmentedCell. Most NSSegmentedCell methods have covers in NSSegmentedControl, which simply call the NSSegmentedCell equivalent. For more information, see the NSSegmentedCell Class Reference and NSSegmentedControl Class Reference class specifications.

Basic Configuration

A segmented control requires some basic configuration. You must specify its tracking mode—the way in which selections are handled; how many segments it contains; and, optionally, the width of each segment. Segmented controls support three different tracking modes:

You can configure a segmented control programatically or using Interface Builder. In Cocoa, the tracking mode is set using an NSSegmentedCell method. Since connections are usually made to the control that contains the cell, you typically have to access the cell first and then send the message, if you are setting the tracking mode programmatically.

Text Labels and Images

You can set a text label (title) or image independently for each segment. By default, each segment autosizes to fit its contents. If you want to ensure a fixed size—perhaps with each segment the same width—you must set the width of each segment individually. In this case it is up to you to ensure that each segment is wide enough for its contents. If a segment is too narrow for its contents, text is truncated and images are clipped.

Menus

A segment can have a menu; you can configure this menu programatically or in Interface Builder. You then set the menu for a segment programatically, using the setMenu:forSegment: method. You typically set a menu together with a label or an image. If you do not specify either, the segment remains blank, although the menu will appear when the user clicks on it.