ios學習筆記(三)UISlider與UISwitch控件

jopen 12年前發布 | 27K 次閱讀 IOS iOS開發 移動開發

1 首先我們還是創建一個Single View Application,然后打開MainStoryboard_iphone.storyboard,在IB中添加一個UISlider控件和一個Label,這個Label用來顯示Slider的值。

選中新加的Slider控件,打開Attribute Inspector,修改屬性值,設置最小值為0,最大值為100,當前值為0.5,并確保勾選上Continuous,如下圖:

ios學習筆記(三)UISlider與UISwitch控件

接著我們放上UISwitch控件,就是很像開關的那種控件,它只有兩個狀態:on和off,全都放上去效果就是這樣的:

ios學習筆記(三)UISlider與UISwitch控件

 

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</uikit></pre>
    接著是實現 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</pre>
    3.剩下的就是連接操作和輸出口:

    將slider控件的value changed事件與sliderChanged方法連接在一起,將swich控件的value changed事件與swichChanged方法連接在一起,當然還要把lable控件和swich控件的輸出與ViewController的相應控件接口連接在一起。

    最終實現的效果如下面兩張圖:                                                         

    ios學習筆記(三)UISlider與UISwitch控件

     

    ios學習筆記(三)UISlider與UISwitch控件             


 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!