In this post I will demonstrate on how to use a slider control.
Overview: In this post we will change the value of text as per the value of the slider,
Step 1: Open Xcode and create a window based or a view based project and add two UIViewController subclass give an appropriate name to the file and select the .h file of the viewController subclass and add this piece of code. The name of my viewcontroller class is sliderviewController.
#import <UIKit/UIKit.h>
@interface sliderviewController : UIViewController {
UILabel *mylabel;
UISlider *slider;
}
-(void)changeLabelText;
@end
in the above code you can see that I have made the objects of the label and slider also I have made a function called changeLabelText which will be called by the slider
Step 2: In this step we will go to the .m file of sliderviewController and perform some settings like setting the frame and text for the label and slider control into the init method here's how we do that
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
// Custom initialization
mylabel = [[UILabel alloc]initWithFrame:CGRectMake(117, 139, 93, 21)];
mylabel.text = @"Default text";
slider = [[UISlider alloc]initWithFrame:CGRectMake(30, 201, 252, 22)];
slider.maximumValue = 100;
slider.minimumValue = 1;
[slider addTarget:self action:@selector(changeLabelText)forControlEvents:UIControlEventValueChanged];
}
return self;
}
In the above code for the slider control I have set the max and min value properties by default the min value is zero and max value is one. Now into the loadView method add these views to your current view
- (void)loadView {
[super loadView];
[self.view addSubview:mylabel];
[self.view addSubview:slider];
}
Step 3: Now coming to our function named changeLabelText, here's how it looks
-(void)changeLabelText
{
mylabel.text = [NSString stringWithFormat:@"%.f",slider.value];
}
In the above code I have changed the text of the label as per the value of the slider since the value of the slider is a float value so I have used %.f in order to avoid the decimal part.
Step 4: In this step you have to select the AppDelegate.m file of your project and add this viewController subclass to your iPhone window, here's how its done
#import "SliderDemoAppDelegate.h"
#import "sliderviewController.h"
@implementation SliderDemoAppDelegate
@synthesize window;
- (void)applicationDidFinishLaunching:(UIApplication *)application {
// Override point for customization after application launch
sliderviewController *sliderVC = [[sliderviewController alloc]init];
[window addSubview:sliderVC.view];
[window makeKeyAndVisible];
}
Step 5: Build and Go that means Run the application and you are done you will get the following output.
I hope this post was helpful...
No comments:
Post a Comment