Latest in Coding

Image credit:

iPhone Coding: Using the Slider


In terms of application development, the iPhone's UISlider is pretty standard. It works like nearly every other slider you've ever programmed. It offers a drag-able thumb control that moves between a minimum and maximum value. As its dragged, the slider produces events that you can redirect to your main application.

Creating the Slider

To create a slider, you allocate it and initialize it with a frame just like any other UIKit control:

slider = [[UISliderControl alloc] initWithFrame: CGRectMake(0.0f, 32.0f, 320.0f, 20.0f)];

Next, you specify its minimum and maximum values with the setMinValue: and setMaxValue: calls. The "setShowValue" call is optional. When set to YES, it displays the current value to the right of the slider (as shown here) so the user gets instant feedback.

[slider setMaxValue:100.0f];
[slider setMinValue:0.0f];
[slider setShowValue:YES];

Now you must add a target for events. Here, I tell the slider to issue the handleSlider: method for mouse dragged events. Fortunately, the iPhone seems to use standard NextStep event equivalents, so 7 corresponds to NSRightMouseDragged, 1 to NSLeftMouseDown and 2 to NSLeftMouseUp. Since the iPhone only supports one button, the right and left gets a little confused.

[slider addTarget:self action:@selector(handleSlider:) forEvents:7];

Next, add the behavior for the message that gets called. In this example, I just write the [slider value] to a text view.

[textView setText:[NSString stringWithFormat:@"End Value: %f", [slider value]]];

To finish up, I added a custom version of objc_msgSend_fpret that was floating around the 'net. Early versions of the iPhone toolchain (which includes most of the installed base at this time) do not support messages that return floating point values. This function adds that ability back. If you've installed version 0.20 of the SVN, you can omit this extra function.





From around the web

ear iconeye icontext file