iPhone控件之UISlider

 1 //
2 // UITestViewController.m
3 // UITest
4 //
5
6 #import "UITestViewController.h"
7
8 UILabel *lblSliderValue;
9
10 @implementation UITestViewController
11
12 -(void)sliderAction:(id)sender
13 {
14 int stepAmount = 10;
15 float stepValue = (abs([(UISlider *)sender value]) / stepAmount) * stepAmount;
16 [sender setValue:stepValue];
17
18 lblSliderValue.text = [NSString stringWithFormat:@"%d",(int)stepValue];
19 }
20
21
22 - (void)viewDidLoad {
23
24 [super viewDidLoad];
25
26 CGRect sliderRect = CGRectMake(20,50,280,40);
27 UISlider *mySlider = [[UISlider alloc] initWithFrame:sliderRect];
28
29 mySlider.minimumValue = 0;
30 mySlider.maximumValue = 100;
31 mySlider.continuous = YES;
32
33 //images
34 UIImage *leftTrackImage = [[UIImage imageNamed:@"left_slider.png"] stretchableImageWithLeftCapWidth:5.0 topCapHeight:0.0];
35 UIImage *rightTrackImage = [[UIImage imageNamed:@"right_slider.png"] stretchableImageWithLeftCapWidth:5.0 topCapHeight:0.0];
36 UIImage *thumbImage = [UIImage imageNamed:@"apple_thumb.png"];
37 UIImage *minSliderImage = [UIImage imageNamed:@"apple_min.png"];
38 UIImage *maxSliderImage = [UIImage imageNamed:@"apple_max.png"];
39
40 [mySlider setThumbImage:thumbImage forState:UIControlStateNormal];
41 [mySlider setMinimumTrackImage:leftTrackImage forState:UIControlStateNormal];
42 [mySlider setMaximumTrackImage:rightTrackImage forState:UIControlStateNormal];
43 [mySlider setMinimumValueImage:minSliderImage];
44 [mySlider setMaximumValueImage:maxSliderImage];
45 [mySlider setValue:50.0f];
46
47 //handle value change events
48 [mySlider addTarget:self action:@selector(sliderAction:) forControlEvents:UIControlEventValueChanged];
49
50 //label to show current value
51 CGRect lblRect = CGRectMake(145,100,100,20);
52 lblSliderValue = [[UILabel alloc] initWithFrame:lblRect];
53 lblSliderValue.backgroundColor = [UIColor clearColor];
54
55 lblSliderValue.text = [NSString stringWithFormat:@"%d",(int)mySlider.value];
56
57 //add slider to main view
58 [self.view addSubview:mySlider];
59 [self.view addSubview:lblSliderValue];
60
61 [lblSliderValue release];
62 [mySlider release];
63 }
64
65 - (void)didReceiveMemoryWarning {
66 // Releases the view if it doesn't have a superview.
67 [super didReceiveMemoryWarning];
68
69 // Release any cached data, images, etc that aren't in use.
70 }
71
72 - (void)viewDidUnload {
73 // Release any retained subviews of the main view.
74 // e.g. self.myOutlet = nil;
75 }
76
77
78 - (void)dealloc {
79 [super dealloc];
80 }
81
82 @end
posted @ 2012-03-13 13:13  FoxBabe  阅读(311)  评论(0编辑  收藏  举报