本範例目的是使用按鈕(button)去改變開關(UISwitch)之狀態, 並取得切換狀態的值, 

程式執行後, 點選Switch印出switch的status

1. storyboard中加入switch, button

2.與viewcontroller.h檔建立程式關聯性, 程式碼如下

@property (strong, nonatomic) IBOutletUISwitch *mySwitch;

- (IBAction)toClick:(id)sender;

- (IBAction)switchChanged:(id)sende//switch再建置一個action動作,並在m檔中實作此動作內容

3.點擊按鈕, 判斷switch狀態並切換, 程式碼如下

- (IBAction)toClick:(id)sender {

    if(_mySwitch.on == YES)
    {
        [_mySwitch setOn:NO animated:YES];
    }else{
        [_mySwitch setOn:YES animated:YES];
    }
}

4.實作- (IBAction)switchChanged裡頭的方法

- (IBAction)switchChanged:(id)sender {

     NSLog(@"%d", _mySwitch.on); //印出switch的status
}

 

//viewcontroller.h程式碼內容

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController
 
@property (strong, nonatomic) IBOutletUISwitch *mySwitch;

- (IBAction)toClick:(id)sender;
 
@end

//viewcontroller.m程式碼內容

#import "ViewController.h"

@interfaceViewController ()

@end

@implementation ViewController

 
- (IBAction)toClick:(id)sender {

    if(_mySwitch.on == YES)
    {
        [_mySwitch setOn:NO animated:YES];
    }else{
        [_mySwitch setOn:YES animated:YES];
    }
}


- (IBAction)switchChanged:(id)sender {

     NSLog(@"%d", _mySwitch.on); //印出switch的status
}
 
@end

UISwitch-按鈕改變開關狀態

arrow
arrow
    文章標籤
    iOS objective c UISwitch
    全站熱搜

    Will 發表在 痞客邦 留言(0) 人氣()