UISwitch的使用

1、我们先在界面上实现一个 UISwitch。

在 控制器.m 文件中,添加一个UISwitch的属性。

 1 @interface moboViewController ()

2 @property (nonatomic, strong) UISwitch *mainSwtich;

3 @end 

在 - (void)viewDidAppear 方法中实例化一个 UISwitch 并添加到界面上。

 1 - (void)viewDidAppear:(BOOL)animated
 2 {
 3     [super viewDidLoad];
 4     
 5     self.mainSwtich = [[UISwitch alloc]initWithFrame:CGRectMake(100, 100, 0, 0)];//实例化,坐标为 x100,y100
 6     
 7     [self.view addSubview:self.mainSwtich];   //添加到界面
 8 }

2、自定义开关颜色:

我们首先按住 cmd,进入UISwitch头文件。看到三个属性:
这里写图片描述

UIColor *onTintColor  // 开启时颜色

UIColor *tintColor    // 关闭时颜色

UIColor *thumbTintColor // 开关按钮颜色

下面我们来自定义一下,在- (void)viewDidAppear中添加如下代码:

 self.mainSwtich.thumbTintColor = [UIColor colorWithRed:(151./255.0) green:(81./255.0) blue:(229./255.0) alpha:1];

  self.mainSwtich.tintColor = [UIColor colorWithRed:(51./255.0) green:(181./255.0) blue:(229./255.0) alpha:1];

 self.mainSwtich.onTintColor = [UIColor colorWithRed:(51./255.0) green:(181./255.0) blue:(229./255.0) alpha:1];

注:我们用到了UIColor 类的 colorWithRed:green:blue: 方法,这个方法的色值是浮点型,所以必须用”色值./255.0”,色值最好后面带一个 . ,显得专业一点~~~

  另外色值转换神马的,有一个网站支持在线转换:http://www.atool.org/colorpicker.php

3、我们来设定UISwitch的默认开关状态:

这个很简单,在 - (void)viewDidAppear方法中添加如下代码:

  [self.mainSwtich setOn:YES animated:YES]; 

4、监听 UISwitch 的开关状态:

  [self.mainSwtich addTarget:self action:@selector(switchIsChanged:) forControlEvents:UIControlEventValueChanged]; 

再在- (void) viewDidAppear 下面,实现一下 switchIsChanged 方法:

 - (void)switchIsChanged:(UISwitch *)paramSender
 {
     if ([self.mainSwtich isOn]) {
         NSLog(@"Switch is on");
     }
     else{
         NSLog(@"Switch is off");
     }
 }

猜你喜欢

转载自blog.csdn.net/BeanGo/article/details/78470138