ViewController.m
// ViewController.m
// UISwitch
//
// Created by mac on 2016/10/27.
// Copyright © 2016年 mac. All rights reserved.
//
#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.
// 创建一个开关对象
// 继承于UIView的
_mySwitch = [[UISwitch alloc] init];
// 苹果官方发控件的位置设置
// 位置X,Y的值可以改变
// 宽度和高度的值无法改变
_mySwitch.frame = CGRectMake(100, 100, 100, 100);
// 开关状态设置属性
// YES:开启状态
// NO:关闭状态
_mySwitch.on =YES;
// 也可以使用set函数
[_mySwitch setOn:YES];
// 设置开关状态
// p1:状态设置
// p2:是否开启动画
[_mySwitch setOn:YES animated:NO];
[self.view addSubview:_mySwitch];
// 设置整体风格(关闭的时候的风格)
[_mySwitch setTintColor:[UIColor orangeColor]];
// 设置开启状态的风格颜色
[_mySwitch setOnTintColor:[UIColor whiteColor]];
// 开关原按钮的风格颜色
[_mySwitch setThumbTintColor:[UIColor blueColor]];
// 开关控件添加以恶搞事件函数
// p1:实现函数对象
// p2:函数对象
// p3:事件响应时代事件类型UIControlEventValueChanged:状态发生变化触发函数
[_mySwitch addTarget:self action:@selector(swChange:) forControlEvents:UIControlEventValueChanged];
}
// 参数传入的就是开关对象本身
-(void) swChange:(UISwitch*) sw
{
//on表示当前结束的状态
if(sw.on ==YES)
{
NSLog(@"开关被打开!");
}else{
NSLog(@"开关被关闭!");
}
NSLog(@"变化");
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
ViewController.h
// ViewController.h
// UISwitch
//
// Created by mac on 2016/10/27.
// Copyright © 2016年 mac. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController
{
// 定义一个开关控件
// 可以进行状态改变
// 开:关:两种状态可以进切换
// 所有UIKit框架库中的控件均以UI开头
// 苹果官方的控件都定义在UIkit框架库中
UISwitch* _mySwitch;
}
@property(retain , nonatomic) UISwitch* mySwitch;
@end