1 首先我們還是建立一個Single View Application,然後開啟MainStoryboard_iphone.storyboard,在IB中添加一個UISlider控制項和一個Label,這個Label用來顯示Slider的值。
選中新加的Slider控制項,開啟Attribute Inspector,修改屬性值,設定最小值為0,最大值為100,當前值為0.5,並確保勾選上Continuous,如:
接著我們放上UISwitch控制項,就是很像開關的那種控制項,它只有兩個狀態:on和off,全都放上去效果就是這樣的:
2.好了我們開始寫代碼嘍:ViewController.h:
#import <UIKit/UIKit.h>@interface ViewController : UIViewController{ UILabel *sliderlabel; UISwitch *leftSwitch; UISwitch *rightSwitch;}@property (nonatomic,retain) IBOutlet UILabel *sliderlabel;@property (nonatomic,retain) IBOutlet UISwitch *leftSwitch;@property (nonatomic,retain) IBOutlet UISwitch *rightSwitch;- (IBAction)sliderChanged:(id)sender;- (IBAction)switchChanged:(id)sender;@end
接著是實現 ViewController.m:
#import "ViewController.h"@interface ViewController ()@end@implementation ViewController@synthesize sliderlabel;@synthesize leftSwitch;@synthesize rightSwitch;- (void)viewDidLoad{ [super viewDidLoad];// Do any additional setup after loading the view, typically from a nib.}- (void)viewDidUnload{ [super viewDidUnload]; // Release any retained subviews of the main view.}- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation{ if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) { return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown); } else { return YES; }}- (IBAction)sliderChanged:(id)sender{ UISlider *slider=(UISlider*)sender; int progressAsInt=(int)(slider.value+0.5f); NSString *newText=[[NSString alloc] initWithFormat:@"%d",progressAsInt]; sliderlabel.text=newText; [newText release]; NSLog(@"%d",progressAsInt);}- (IBAction)switchChanged:(id)sender{ UISwitch *whichSwich=(UISwitch *)sender; BOOL setting=whichSwich.isOn; [leftSwitch setOn:setting animated:YES]; [rightSwitch setOn:setting animated:YES];}- (void)dealloc{ [sliderlabel release]; [leftSwitch release]; [rightSwitch release]; [super dealloc];}@end
3.剩下的就是串連操作和輸出口:
將slider控制項的value changed事件與sliderChanged方法串連在一起,將swich控制項的value changed事件與swichChanged方法串連在一起,當然還要把lable控制項和swich控制項的輸出與ViewController的相應控制項介面串連在一起。
最終實現的效果如下面兩張圖: