Unlike buttons, switches and sliders retain a value. A switch is just that, as shown in Figure 10-5.
It presents a sliding button that can change between “on”and “off” values by either tapping or swiping it with your finger. You see these everywhere in iOS, as shown on the right in Figure 10-5.
Figure 10-5. Switches, sliders, and the Settings app
A UISwitch object has a single Boolean value property named, appropriately enough, on. Getting that property will tell you which position the switch is in. Setting the property changes it. You can request that UISwitch perform alittle animation eye-candy, when you change its value programmatically,
by sending it the -setOn:animated: message, passing YES for the animated parameter.
A number of properties let you customize your switch’s appearance:
n tintColor, onTintColor, and thumbTintColor: the first two set the colors used when the switch is off and on. The thumbTintColor makes the “thumb” of the switch (the circle you drag) a different color thantintColor.
n onImage and offImage: normally a switch displays either (localized) “On” or “Off” text titles next to the thumb. You can replace these with images of your choosing. There are important size restrictions, soread the documentation.
Like most controls with a value, a switch sends a “value changed” event (UIControlEventValueChanged) whenever the user changes it. Connect this event to your controller to receive an action message when the switch is flipped.
Sliders, also shown in Figure 10-5, are another input control that lets the user choose a value by dragging a slider to a position within a predetermined range. While a switch’s value is Boolean,
a slider’s value property is a floating-point value that represents a continuous range of numbers.
The slider’s value property is constrained to the range set by the minimumValue and maximumValue properties. These default to 0 and 1, respectively. Unless you change those, value will be a fractional number between 0 and 1 (inclusive).
The key visual customization properties are:
n minimumTrackTintColor, maximumTrackTintColor, and thumbTintColor: changes the colors of the tracks (to the left and right of the thumb), as well as the thumb itself. See the Customized Slider in theUICatalog (Figure 10-4) for an example, and the code that does it.
n minimumValueImage, maximumValueImage, thumbImage (per state): like the slider, you can change the image used to draw the tracks of the slider, and the thumb itself. The thumb image works like UIButton’simage, in that you can supply different images for different states (normal, highlighted, and disabled).
A slider sends a single “value changed” event when the user moves it, unless you set the continuous
property to YES. If you set continuous, the control fires a barrage of “value changed” messages as the user drags the slider. You used this setting in the ColorModel app in Chapter 8 so color changes happened “live” as youdragged around a slider.
Page Control
A page control (UIPageControl) object, shown in Figure 10-6, can be thought of as a discrete slider control. As its name implies, it’s intended to indicate the user’s position within a small (up to 20) number of pages or items.Apple’s Weather app uses it to indicate which location the user is currently viewing, shown on the right in Figure 10-6.
Figure 10-6. Page control and Weather app
UIPageControl’s integer currentPage property is its value, and its numberOfPages property determines the former’s range and the number of dots that appear. Its appearance can be slightly modified with these properties:
n pageIndicatorTintColor: sets the color for the page indicator
n hidesForSinglePage: if set to YES, the control doesn’t draw anything if there’s only one page (numberOfPages<=1).
Tapping a page control object to the right or left of the current page either decrements or increments the currentPage property (moving forwards or backwards one page) and sends a “value changed” event.
Steppers
A stepper (UIStepper) has the face of UIButton and the heart of UIPageControl, as shown in
Figure 10-7. It displays two buttons, side by side. Use a stepper when your user needs to increase or decrease something—“something” is up to you, the stepper doesn’t display a value—one step at a time.
Figure 10-7. Stepper
Like a slider, the stepper’s minimumValue and maximumValue properties set the range for its value property. The stepValue property determines what “one step” means. As an example, Table 10-1 would be the property values you’dset for a stepper with 11 possible values, between 1.0 and 6.0.
Table 10-1. Property values for a stepper with 11 possible values (1.0 to 6.0, inclusive)
Property Value
minimumValue 1.0 maximumValue 6.0 stepValue 0.5
A stepper’s visual appearance can be customized using increment, decrement, and background images, which you set the same way you do for a button. There’s also a UIButton-ish tintColor property.
A stepper sends a “value changed” action every time the user taps the increment or decrement button. There are three properties that alter this behavior:
n continuous: the continuous property works just like is does for the slider.
n autorepeat: setting autorepeat to YES allows the user to continuously change the value (one step at a time) by holding down one of the buttons.
n wraps: this property lets the value “wrap” around the range. Using the example inTable 10-1, tapping + when the value was already a 6.0 would change the value back to 1.0. When wraps is YES, the buttonsdo not disable when the value is at the beginning or end of the range.
Segmented Controls
Closely related to steppers is the UISegmentedControl class. A segmented control displays multiple segments. Each segment acts as a button for a choice, as shown in Figure 10-8. Use a segmented control when you wantthe user to pick between a small number of mutually exclusive choices.
Figure 10-8. Segmented controls
Segmented controls come in four flavors: plain, bordered, bar, and bezeled. The UICatalog app demonstrates the first three. The bar and bezeled styles can be tinted by setting the tintColor property, also demonstrated in UICatalog.
To use a segmented control, first tell it how may segments there are by setting the numberOfSegments property. You can then set the label of each segment to either a string title or an image using one of these methods:
- (void)setTitle:(NSString *)title forSegmentAtIndex:(NSUInteger)segment
- (void)setImage:(UIImage *)image forSegmentAtIndex:(NSUInteger)segment
Alternatively, you can choose to insert (or remove) segments one at a time. Using these methods, you have the option of having the view animate the change, sliding and resizing the other segments to make room:
- (void)insertSegmentWithTitle:(NSString *)title atIndex:(NSUInteger)segment animated:(BOOL)animated
- (void)insertSegmentWithImage:(UIImage *)image atIndex:(NSUInteger)segment animated:(BOOL)animated
A segmented control sends a “value changed” event (UIControlEventValueChanged) when the user changes it. Its selectedSegmentIndex property tells you which segment is selected, or can be used to change that. The specialvalue UISegmentedControlNoSegment means no segment is selected.
Normally, the buttons in a segment are “sticky”—they stay down to indicate which segment is selected. If you set the momentary property to YES, buttons don’t stay down and the selectedSegmentIndex goes back toUISegmentedControlNoSegment when the user removes their finger.
Progress Indicators
iOS provides two progress indicators, UIActivityIndicatorView and UIProgressView, that provide your users feedback during time-consuming activities, or to display relative quantities (such as the amount of storage used), asshown in Figure 10-9. Use these to let your user know that your app is hard at work; they should remain calm and stay in their seats, with their seatbelts securely fastened.
Figure 10-9. Activity and progress indicator
The UIActivityIndicatorView is often called a “spinner” or “gear.” Use it when space is limited or the duration of the activity is indeterminate or unknown. There are three spinner styles to choose from: small grey(UIActivityIndicatorViewStyleGray), small white
(UIActivityIndicatorViewStyleWhite), and large white (UIActivityIndicatorViewStyleWhiteLarge).
Using a spinner is easy. Send it a -startAnimating message to start it spinning, and -stopAnimating
to stop it again. Its hidesWhenStopped and color properties are self-explanatory.
The second indicator is the progress bar (UIProgressView). It presents a progress indicator, familiar to anyone who’s had days of their life siphoned away waiting on computers to finish something.
The view has two looks:
n UIProgressViewStyleDefault: the regular style progress bar
n UIProgressViewStyleBar: a style designed to be used in a toolbar
You control the view by periodically setting its progress property to a value between 0 (empty) and 1 (full). Setting the progress property makes the indicator jump to that position. By sending
-setProgress:animated: you can ask the indicator to smoothly animate to the new setting, which is less jarring for big changes.
Use the trackImage or trackTintColor properties to customize the look of the unfinished segment of the view, and the progressImage and progressTintColor properties to adjust the finished
segment. The UICatalog app has a Tint button in the toolbar that demonstrates what happens when
progressTintColor and trackTintColor are set to blue.
Text Views
Text views come in three flavors: labels, text fields, and text views. The label is the simplest. It’s used to place a single string of text in your interface, often next to another field or view to explain its purpose, which is where itgets its name. A text field is a general-purpose input field, providing full-featured editing for a single line of text. A text view can display, and edit, multiple lines of text. Let’s start with the simple one.
Labels
You see labels everywhere in iOS (see practically any figure in this book), and you’ve used them numerous times in your own projects. Use a UILabel object wherever you simply want to display some text, for whatever purpose.Use label object as labels by setting their text in Interface Builder and forgetting about them—no connection required. If you connect the label to an outlet, your controller can update the text, as you did in the ColorModel app.
Labels have a select number of properties that let you alter how the text string is displayed, as listed in Table 10-2.
numberOfLines The maximum number of lines the label will display, normally 1. Set it to
0 to display as many lines as are needed. font
The text’s font (face, size, and style) textColor
The color used to draw the text
textAlignment One of left, center, right, justified, or natural. Natural employs the native alignment of the font.
attributedText Draws an attributed string, instead of the simple text property. Use this to display text with a mixture of different fonts, sizes, styles, and colors. The text attributes in the string override the other text styleproperties (font, textColor, shadowOffset, and so on).
lineBreakMode Determines how an overly long string is made to fit in the available space of the view.
adjustsFontSizeToFitWidth An alternative to shortening the string, it makes the text smaller so the whole string will fit.
If you plan on displaying a variable amount of text, pay attention to the properties that control what happens when the string is too big to fit in the view. First are the numberOfLines and lineBreakMode properties. The line breakmode controls how the string is broken up across multiple lines. The choices for multiple line labels (numberOfLines!=1) are to break text at the nearest character (NSLineBreakByCharWrapping) or at the nearest word(NSLineBreakByWordWrapping).
For single line labels (numberOfLines==1), text that won’t fit in the view is either unceremoniously cut off (NSLineBreakByClipping), or a portion of the beginning (NSLineBreakByTruncatingHead), middle(NSLineBreakByTruncatingMiddle), or end (NSLineBreakByTruncatingTail) of the string is replaced by an ellipsis (...) character.
The alternate method of getting text to fit is to set the adjustsFontSizeToFitWidth or adjustLetterSpacingToFitWidth properties to YES. These options cause either the spacing between words, or the size of the font—you can alsoset both—to be reduced in an attempt to make the string fit in the available space. The spacing between words will never be reduced to nothing and
its size will never be shrunk below the minimumScaleFactor property. If the text still won’t fit, the lineBreakMode is applied.
Text Fields
Use a text field (UITextField) when you want the user to enter or edit one line of text. The Shorty app used a text field to get an URL from the user.
The UICatalog app demonstrates four text fields, as shown in Figure 10-10.
Consistent with the complexity of editing almost any kind of text, you have a broad range of choices when it comes to the view’s appearance andbehavior.
Figure 10-10. Text fields
Let’s start with the appearance of the field. There are four basic style to choose from, controlled by the borderStyle property:
n UITextBorderStyleBezel: surrounds the field with a chiseled border, giving the illusion of the field being inset.
n UITextBorderStyleRoundedRect: draws a simple rounded rectangle around the field.
n UITextBorderStyleLine: draws a thin grey rectangle around the field
n UITextBorderStyleNone: does not draw a border
The UICatalog app only demonstrates the bezel and rounded rectangle style, but the other two aren’t hard to imagine. You can provide a more dramatic look by setting the background property to your own UIImage. Thebackground property overrides the borderStyle property. In other words, you can’t supply a background image for a chiseled border; if you want that look, your image will need to include a chiseled border.
The placeholder property shows a string (in light grey) when the field is empty. Use this to prompt the user (like “Your Name Here”), or possibly show a default value. Set the clearsOnBeginEditing to YES if you want the text in thefield to be automatically cleared before the user begins typing.
The font face, size, style, and color of the text in the field can be controlled either by setting the font and textColor properties, or by using attributed text strings. The latter is considerably more complicated and considerablymore flexible.
You can also insert accessory views in three different places. Use these to add additional controls or indicators, such a button that pops up a set of options for the field, or a progress indicator. The accessory view propertiesare:
n leftView and leftViewMode
n rightView and rightViewMode
n inputAccessoryView
The left and right views can be any UIView object that will fit inside the text field. The UICatalog app demonstrates this by adding a UIImageView to the text field. The appearance of both right and left views are controlled by their companion rightViewMode and leftViewMode properties. Each can be set to never display the view, always display the view, only display the view when editing, or only display the view when not editing.
The input accessory view doesn’t get attached to the text field. Instead, it gets attached to the top of the virtual keyboard that appears when the user begins editing. You can use an input accessory view to add special controls,presets, options, and so on.
Text fields send a variety of events. The most useful are the “editing did end on exit” event
(UIControlEventEditingDidEndOnExit), sent when the user stops editing a field, and the “value changed”
event (UIControlEventValueChanged), sent whenever the text in the field is modified. You connected actions to both of these events in the MyStuff app. To receive even more editing-related messages, and exert some control over editing, create a delegate object for the text field (UITextFieldDelegate). The delegate receives messages when editing begins and ends, and it can also control if editing is allowed to begin, editing is allowed to end, or a specific change is allowed to be made.
Text Editing Behavior
There are a dizzying number of properties that affect how text in a field is edited. If you look in the documentation for UITextField, you won’t find any of them. That’s because they are defined in the UITextInput andUITextInputTraits protocols, which UITextField and UITextView both adopt. The number of properties and options are almost overwhelming, so I’ve listed the highlights in Table 10-3.
autocapitalizationType Controls the auto-capitalization mode: off or capitalize sentences, words, or characters
autocorrectionType Turns auto-correction on or off
spellCheckingType Turns spell checking, suggestions, and dictionary lookup on or off
keyboardType Chooses the virtual keyboard to use (normal, URL, just numbers, telephone dial, email address, Twitter, and so on)
returnKeyType If the keyboard has a “go” key, this property determines how it’s labeled:
Go, Google, Join, Next, Route, Search, Send, Yahoo!, Done, or Emergency Call.
Text Views
Text views (UITextView) objects are the synthesis of labels and text fields. It’s not a subclass of either, but it essentially inherits the capabilities of both, and adds a few extra features of its own. Whether a text view can beedited or not is controlled by its editable property.
With editable set to NO, a text view act much like a multi-line label. It displays multiple lines of text in a variety of fonts, sizes, and styles, with control over line breaks. To this it adds some additional talents: scrolling,selection, and data detectors.
Unlike a label, if the text won’t fit in the vertical space of view, the user can scroll the text in the view to see the rest of it. You used this feature in the Surrealist app.
The user can select text in a text view (by touching and holding on the text). The selected text can be copied to the clipboard or used to look up words in the dictionary. In addition, you can enable data detectors. Datadetectors are a technology that recognizes the purpose of certain text (such as a telephone number or someone’s email address). The user can then tap the text to do something useful (place a phone call, address a new emailmessage, and so on).
With the editable property set to YES, the text view becomes a (miniature) word processor. The user can type, select, cut, copy, and paste to their heart’s content. All of the editing features and options described in the “TextFields” section apply to text views. About the only thing missing are the borders; text views do not draw a border.
A text view is also capable of editing styled (attributed) text, but you’ll have to supply the additional user interface elements that allow the user to choose a font face, size, style, color, and so on. The text view will handle themechanics of applying those styles to what the user is typing, but your controller will have to tell the text view what those styles are.
Use a text view, instead of a label or text field, when:
n The user needs to edit multi-line text
n There’s more text than will fit in the view and you want it to scroll
n You want the user to have the ability to select and copy text or look up definitions
n You want to use data detectors






No comments:
Post a Comment