头文件
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController{
//定义开关文件
UISwitch* _uiSwitch;
}
//定义属性uiSwitch
@property(retain, nonatomic) UISwitch* uiSwitch;
@end
源文件
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
//同步属性和成员变量
@synthesize uiSwitch = _uiSwitch;
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
//初始化uiSwitch
_uiSwitch = [[UISwitch alloc]init];
//位置可改变、宽高是固定的所以无法改变,即后面两个数值无效
_uiSwitch.frame = CGRectMake(100, 100, 200, 100);
//开关开启
_uiSwitch.on = YES;
//[_uiSwitch setOn:YES];
//[_uiSwitch setOn:YES animated:YES];
//设置开启颜色
[_uiSwitch setOnTintColor:[UIColor orangeColor]];
//开关控件添加事件
[_uiSwitch addTarget:self action:@selector(onswitch) forControlEvents:UIControlEventValueChanged];
[self.view addSubview:_uiSwitch];
}
-(void) onswitch{
if(_uiSwitch.on == YES){
NSLog(@"开关被打开");
}else{
NSLog(@"开关被关闭");
}
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
网友评论