正如分段控件代替了单选按钮,开关也代替了点选框,一般来说我的和设置页面经常常需要这种开关的需求,我们就来看看吧!
首先介绍一下switch控件
switch在UIKit框架之下,继承自UIControl,可以添加触发事件。开关状态下默认的样式如下.
点进去UISwitch,可以发现switch有以下的属性和方法:
属性:
onTintColor UIColor 开状态下的颜色
tintColor UIColor 关状态下的颜色
thumbTintColor UIColor 滑块颜色
onImage UIImage 无效
offImage UIImage 无效
on( isOn) BOOL isOn是用来获取状态的是get方法,on可以用来设置开关
方法:
- (instancetype)initWithFrame:(CGRect)frame; // This class enforces a size appropriate for the control, and so the frame size is ignored.它有默认size,因此frame的size可以忽略,即使你定制了size系统也会忽略掉。
- (nullable instancetype)initWithCoder:(NSCoder *)aDecoder;
- (void)setOn:(BOOL)on animated:(BOOL)animated; // does not send action
⚠️:虽然系统默认switch的size,但是switch的size也不是不能变的,我们可以通过缩放来改变switch的大小,如果还是不能满足你的需求,那你就需要自定义啦!
Objective-C代码:
//2. create switch
self.mainSwitch = [[UISwitch alloc] initWithFrame:CGRectMake(100, 70, 0, 0)];
[self.view addSubview:self.mainSwitch];
//缩小或者放大switch的size
self.mainSwitch.transform = CGAffineTransformMakeScale(0.5, 0.5);
self.mainSwitch.layer.anchorPoint = CGPointMake(0, 0.3);
// self.mainSwitch.onImage = [UIImage imageNamed:@"on.png"]; //无效
// self.mainSwitch.offImage = [UIImage imageNamed:@"off.png"]; //无效
// self.mainSwitch.backgroundColor = [UIColor yellowColor]; //它是矩形的
// 设置开关状态(默认是 关)
// self.mainSwitch.on = YES;
[self.mainSwitch setOn:YES animated:true]; //animated
//判断开关的状态
if (self.mainSwitch.on) {
NSLog(@"switch is on");
} else {
NSLog(@"switch is off");
}
//添加事件监听
[self.mainSwitch addTarget:self action:@selector(switchAction:) forControlEvents:UIControlEventValueChanged];
//定制开关颜色UI
//tintColor 关状态下的背景颜色
self.mainSwitch.tintColor = [UIColor redColor];
//onTintColor 开状态下的背景颜色
self.mainSwitch.onTintColor = [UIColor yellowColor];
//thumbTintColor 滑块的背景颜色
self.mainSwitch.thumbTintColor = [UIColor blueColor];
swift代码:
//2. create switch
mainSwitch = UISwitch(frame: CGRect(x: 100, y: 100, width: 0, height: 0))
view.addSubview(self.mainSwitch)
//缩小或者放大switch的size
mainSwitch.transform = CGAffineTransform(scaleX: 0.8, y: 0.8)
mainSwitch.layer.anchorPoint = CGPoint(x:0, y:0.3)
mainSwitch.onImage = UIImage(named:"on.png") //无效
mainSwitch.offImage = UIImage(named:"off.png") //无效
// mainSwitch.backgroundColor = UIColor.yellow //设置背景颜色之后才发现原来它是矩形的
// 设置开关状态(默认是 关)
// self.mainSwitch.isOn = true;
mainSwitch.setOn(true, animated: true) // animated
//判断switch的开关状态
if mainSwitch.isOn {
print("switch is on")
} else {
print("switch is off")
}
//添加监听事件
mainSwitch.addTarget(self, action: #selector(switchAction), for: .valueChanged)
//定制开关颜色UI
//tintColor 关状态下的背景颜色
mainSwitch.tintColor = UIColor.red;
//onTintColor 开状态下的背景颜色
mainSwitch.onTintColor = UIColor.yellow;
//thumbTintColor 滑块的背景颜色
mainSwitch.thumbTintColor = UIColor.blue;
当然,有的项目里的开关UI需要自定义字体或者自定义图片,那么就需要自己自定义switch啦!