当前位置:首页 > 移动开发 > 正文

iOS开关按钮UISwitch控件

开关按钮UISwitch 
在ViewController.h里面

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#import <UIKit/UIKit.h>
 
@interface ViewController : UIViewController{
 
   //定义一个开关控件
   //作用可以进行状态的改变
   //开,关:两种状态可以切换
   //所有UIKit框架库中的控件均已UI开头
   //苹果官方的控件都定义在UIKit框架库中
   UISwitch * _mySwitch;
 
}
 
@property(retain,nonatomic) UISwitch * mySwitch;
 
 
@end

在ViewController.m里面

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
#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的值可以改变(100,100)
   //宽度和高度值无法改变(80,40)写了也没有用的,不会起到作用的。默认的。
   _mySwitch.frame=CGRectMake(100, 200, 180, 40);
 
   //开关状态设置属性
   //YES:开启状态
   //NO:关闭状态
   _mySwitch.on=YES;
 
   //也可以使用set函数
   //[_mySwitch setOn:YES];
 
   //设置开关状态
   //p1:状态设置
   //p2:是否开启动画效果
   //[_mySwitch setOn:YES animated:YES];
 
   [self.view addSubview:_mySwitch];
 
   //设置开启状态的风格颜色
   [_mySwitch setOnTintColor:[UIColor orangeColor]];
 
   //设置开关圆按钮的风格颜色
   [_mySwitch setThumbTintColor:[UIColor blueColor]];
 
   //设置整体风格颜色,按钮的白色是整个父布局的背景颜色
   [_mySwitch setTintColor:[UIColor greenColor]];
 
   //向开关控件添加事件函数
   //p1:函数实现对象
   //p2:函数对象
   //p3:事件响应时的事件类型UIControlEventValueChanged状态发生变化时触发函数
   [_mySwitch addTarget:self action:@selector(swChange:) forControlEvents:UIControlEventValueChanged];
 
 
}
 
//参数传入开关对象本身
- ( void ) swChange:(UISwitch*) sw{
 
   if (sw.on==YES){
     NSLog(@ "开关被打开" );
   } else {
     NSLog(@ "开关被关闭" );
   }
}
 
- ( void )didReceiveMemoryWarning {
   [super didReceiveMemoryWarning];
   // Dispose of any resources that can be recreated.
}
 
@end