用滾動條可以實時改變label的背景色。。假設三個slider,一個控制紅色,一個控制綠色,一個控制藍色
(void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
UILabel *redLabel = [[UILabel alloc] initWithFrame:CGRectMake(20, 300, 70, 30)];
redLabel.text = @"紅色控制";
[self.view addSubview:redLabel];
[redLabel release];
UISlider *redSlide = [[UISlider alloc] initWithFrame:CGRectMake(90, 300, 200, 30)];
redSlide.maximumValue = 1;
redSlide.minimumValue =0;
[redSlide addTarget:self action:@selector(changeRed:) forControlEvents:(UIControlEventValueChanged)];
[self.view addSubview:redSlide];
[redSlide release];
UILabel *greenLabel = [[UILabel alloc] initWithFrame:CGRectMake(20, 360, 70, 30)];
greenLabel.text = @"綠色控制";
[self.view addSubview:greenLabel];
[greenLabel release];
UISlider *GreenSlide = [[UISlider alloc] initWithFrame:CGRectMake(90, 360, 200, 30)];
GreenSlide.maximumValue = 1;
GreenSlide.minimumValue =0;
[GreenSlide addTarget:self action:@selector(changeGreen:) forControlEvents:(UIControlEventValueChanged)];
[self.view addSubview:GreenSlide];
[GreenSlide release];
UILabel *blueLabel = [[UILabel alloc] initWithFrame:CGRectMake(20, 420, 70, 30)];
blueLabel.text = @"藍色控制";
[self.view addSubview:blueLabel];
[blueLabel release];
UISlider *BlueSlide = [[UISlider alloc] initWithFrame:CGRectMake(90, 420, 200, 30)];
BlueSlide.maximumValue = 1;
BlueSlide.minimumValue =0;
[BlueSlide addTarget:self action:@selector(changeBlue:) forControlEvents:(UIControlEventValueChanged)];
[self.view addSubview:BlueSlide];
[BlueSlide release];
self.redColor = arc4random()%256/255.0;
self.greenColor = arc4random()%256/255.0;
self.blueColor = arc4random()%256/255.0;
self.view.backgroundColor = [UIColor colorWithRed:_redColor green:_greenColor blue:_blueColor alpha:1];
}
(CGFloat)changeRed:(UISlider *)slide{
_redColor = slide.value;
// 第一種方法,直接設置
// self.view.backgroundColor = [UIColor colorWithRed:_redColor green:_greenColor blue:_blueColor alpha:1];
//第二種方法,聲明一個返回函數,返回slide.value
return _redColor;
}
(CGFloat)changeGreen:(UISlider *)slide{
_greenColor = slide.value;
// self.view.backgroundColor = [UIColor colorWithRed:_redColor green:_greenColor blue:_blueColor alpha:1];
return _greenColor;
}
(CGFloat)changeBlue:(UISlider *)slide{
_blueColor = slide.value;
// self.view.backgroundColor = [UIColor colorWithRed:_redColor green:_greenColor blue:_blueColor alpha:1];
return _blueColor;
}
(void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}