OC_UISwitch

415 阅读1分钟

UISwitch 是一个可以用于二选一选择的控件,它类似于一个开关,可以选择 off/on 。

UISwitch 创建

UISwitch 的创建方式即为继承于 UIView 的 initWithFrame 方法。

- (instancetype)initWithFrame:(CGRect)frame;

但是要注意这个方法虽然传入一个 frame 属性,但实际上 UISwitchsize 是固定的,所以在调用这个方法的时候, frame 中的 size 属性会被忽略。

属性 类型 解释
on BOOL 表示UISwith的状态
onTintColor UIColor UISwithon = YES 时的颜色
tintColor UIColor UISwithon = NO 时外框颜色
thumbTintColor UIColor UISwith中间滑钮的颜色
onImage UIImage UISwithon = YES 时的图片
offImage UIImage UISwithon = NO 时的图片

监听 UISwitch 属性变化

一般在监听 UISwitch 对象时,我们一般监听他的属性变化,即监听 UIControlEventValueChanged ,如以下例子:

UISwitch *mySwitch = [[UISwitch alloc]initWithFrame:CGRectMake(30, 30, 100, 100)];
// 添加事件
[mySwitch addTarget:self action:@selector(switchChangeValue:) forControlEvents:UIControlEventValueChanged];
[self.view addSubview:mySwitch];

同时我们实现调用的方法

-(void)switchChangeValue:(UISwitch *)sender{
    if (sender.isOn) 
        NSLog(@"switch is on");
    else
        NSLog(@"switch is off");
}

这样我们就可以在按钮状态变化时监听到事件,并且获取按钮的状态。