UISwitch 作為 iOS 系統(tǒng)里面的開關(guān)控件,是一個基本常用的控件,使用也很簡單。
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController
{
// 定義一個開關(guān)控件,控制狀態(tài)的改變
UISwitch* _mySwitch;
}
@property (retain, nonatomic) UISwitch* mySwitch;
@end
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
@synthesize mySwitch = _mySwitch;
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
_mySwitch = [[UISwitch alloc] init];
// x,y 值可以改變,width,height 不能改變
_mySwitch.frame = CGRectMake(100, 200, 0, 0);
// 開關(guān)的狀態(tài), YES 開啟, NO 關(guān)閉
_mySwitch.on = YES;
[_mySwitch setOn:YES animated:YES];
// 設(shè)置開啟狀態(tài)的顏色
[_mySwitch setOnTintColor:[UIColor redColor]];
// 設(shè)置開關(guān)圓形按鈕的顏色
[_mySwitch setThumbTintColor:[UIColor yellowColor]];
// 設(shè)置整體風(fēng)格顏色
[_mySwitch setTintColor:[UIColor grayColor]];
// 設(shè)置事件
[_mySwitch addTarget:self action:@selector(change:) forControlEvents:UIControlEventValueChanged];
[self.view addSubview:_mySwitch];
}
- (void) change:(UISwitch*) sw{
NSLog(@"狀態(tài) = %@", sw.on == YES ? @"開啟" : @"關(guān)閉");
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
基本包含了所有相關(guān)的操作,比較簡單。