iOS入門-09UISwitch

概述

重點

  • UISwitch:開關按鈕
  • UISwitch的屬性和使用

示例代碼

ViewController.h

#import <UIKit/UIKit.h>
@interface ViewController : UIViewController
{
    UISwitch *_uiSwitch;//定義一個成員變量
}

@end

ViewController.m

#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    //初始化
    _uiSwitch = [UISwitch new];
    //蘋果和Android中不同,有些控件的屬性不能設置,是一個固定值比如下面的寬和高
    _uiSwitch.frame = CGRectMake(100, 100, 100, 40);
    //背景色
    //_uiSwitch.backgroundColor = [UIColor orangeColor];
    //設置開關的開閉
//    _uiSwitch.on = YES;
//    [_uiSwitch setOn:YES];
    //加個動畫
    [_uiSwitch setOn:YES animated:YES];
    //開啓時候的顏色風格
    [_uiSwitch setOnTintColor:[UIColor redColor]];
    //開啓時按鈕的顏色
    [_uiSwitch setThumbTintColor:[UIColor orangeColor]];
    //整體顏色
//    [_uiSwitch setTintColor:[UIColor redColor]];
    //開關狀態變化監聽
    //p1:函數實現對象
    //p2:函數對象
    //p3:事件類型(iOS中將各個手勢事件做成了枚舉類型,可以到UIControlEvents中看一下)
    [_uiSwitch addTarget:self action:@selector(swChange:) forControlEvents:UIControlEventValueChanged];
    //添加到父控件
    [self.view addSubview:_uiSwitch];
}

//參數爲開關本身
-(void) swChange:(UISwitch*) sw{
    if (sw.on == YES) {
        NSLog(@"swChange--state==%@",@"on");
    }else{
        NSLog(@"swChange--state==%@",@"closed");
    }
    
}
@end
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章