1.開關(Switch)
- (void)addSwitch:(id)sender { //創建開關對象 UISwitch *pSwitch = [[UISwitch alloc]initWithFrame:CGRectMake(220, 10, 10, 50)]; //為開關設置顏色 pSwitch.backgroundColor = [UIColor redColor]; //給開關添加關聯動作, 方法需要實現 [pSwitch addTarget:self action:@selector(switchMethod:) forControlEvents:UIControlEventValueChanged]; //把開關添加到當前視圖中 [self.view addSubview:pSwitch]; //把開關對象釋放 [pSwitch release]; }
2.分段控件(SegmentControl)
- (void)addSegmentControl:(id)sender { //創建數組,存儲分段的名稱 NSArray *pArray = [NSArray arrayWithObjects:@"1",@"2", nil]; //根據數組對象初始化SegmentControl對象 UISegmentedControl *pSegment = [[UISegmentedControl alloc]initWithItems:pArray]; //設置分段控件的位置 [pSegment setFrame:CGRectMake(10, 240, 300, 40)]; //設置該分段控件的Style [pSegment setSegmentedControlStyle:UISegmentedControlStyleBordered]; //設置分段控件選擇的段數,根據數組存儲的內容 [pSegment setSelectedSegmentIndex:0]; //添加關聯動作,方法需要實現 [pSegment addTarget:self action:@selector(segmentMethod:) forControlEvents:UIControlEventValueChanged]; //把分段控件添加到當前的視圖中 [self.view addSubview:pSegment]; //把創建的對象釋放 [pSegment release]; }3.滑塊(Slider)
- (void)addSlider:(id)sender { //創建UISlider對象,以及位置 UISlider *pSlider = [[UISlider alloc]initWithFrame:CGRectMake(10, 195, 300, 20)]; //設置最小值 pSlider.minimumValue = 0; //最大值 pSlider.maximumValue = 100; //是否可以持續滑動 pSlider.continuous = YES; //設置初始值 pSlider.value = 50; //透明度 self.pImageView.alpha = pSlider.value/100; //最小值處的圖片 pSlider.minimumValueImage = [UIImage imageNamed:@"apple_min"]; //最大值處的圖片 pSlider.maximumValueImage = [UIImage imageNamed:@"apple_max.png"]; //設置當前的圖片 [pSlider setThumbImage:[UIImage imageNamed:@"apple_thumb.png"] forState:UIControlStateNormal]; //添加對應動作,注意:CotrolEvents:valueChanged [pSlider addTarget:self action:@selector(sliderValueChange:) forControlEvents:UIControlEventValueChanged]; //把滑塊添加到當前視圖中 [self.view addSubview:pSlider]; //創建顯示當前值的label self.pShowValueLabel = [[UILabel alloc]initWithFrame:CGRectMake(180, 150, 86, 25)]; //設置背景色 self.pShowValueLabel.backgroundColor = [UIColor lightGrayColor]; //設置當前文本內容 self.pShowValueLabel.text = [NSString stringWithFormat:@"亮度:%%%d",(int)pSlider.value]; //把文本添加到當前視圖中 [self.view addSubview:self.pShowValueLabel]; //把創建的對象釋放 [pSlider release]; }
//滑塊對應的方法,改變圖片的透明度 - (void)sliderValueChange:(UISlider *)slider { //顯示當前亮度 self.pShowValueLabel.text = [NSString stringWithFormat:@"亮度:%%%d",(int)slider.value]; //透明度 self.pImageView.alpha = slider.value/100; }