Slider is a horizontal bar with a slider button which can slide along the bar’s length. The value of the slider changes according to the position of the slider button and this value can be displayed on a label beside the slider. This is precisely what we are going to do in this tutorial.
Slider can be used as a value setter for a particular object such as a volume control.
Step 1: Start Xcode and create a view based application with name “SliderDemo”.
Step 2: Open “SliderDemoViewController.h” and put the following code in it.
01 | @interface SliderDemoViewController : UIViewController { |
06 | @property ( nonatomic ,retain) IBOutlet UILabel *sliderLabel; |
08 | -( IBAction ) sliderChanged:( id ) sender; |
Put the following code in the “SliderDemoViewController.m” file.
01 | @implementation SliderDemoViewController |
02 | @synthesize sliderLabel; |
05 | [sliderLabel release]; |
09 | -( IBAction ) sliderChanged:( id ) sender{ |
10 | UISlider *slider = (UISlider *) sender; |
11 | int progressAsInt =( int )(slider.value + 0.5f); |
12 | NSString *newText =[[ NSString alloc] |
13 | initWithFormat: @"%d" ,progressAsInt]; |
14 | self .sliderLabel.text = newText; |
Here, in the sliderChanged method, we have declared an object of type slider. The variable progressAsInt has been used to store the slider’s position.0.5f is added to the slider value to round it off. We then put the value of progressAsInt in a string and set it as the label’s text.
Step 3: Save(command+s) the project. Now open the “SliderDemoViewController.xib” file from the Resources folder. Add a slider and a label beside it to the view as shown below.
SliderDemoViewController.xib
Open the Attributes Inspector for slider.Set the fields under Values as Minimum = 1,Maximum = 100 and Initial = 50. Step 4: Open the Connections Inspector(command+2) for slider. Connect the value changed link to the sliderChanged method in File’s Owner. Also connect the label to sliderLabel in the File’s Owner.
Step 5: Save,build and run the project. Now as you slide the slider button, the value displayed by the label changes.
You can download the source code here.
OUTPUT:
Output for SliderDemo
Thats the end of the tutorial folks. You are now ready to dabble with your own version of slider
Nguồn: http://www.mobisoftinfotech.com/blog/iphone/iphone-slider-control-uislider-control-tutorial/
Không có nhận xét nào:
Đăng nhận xét