UIKit之UISwitch 开关

#import "TestController.h"

@interface TestController ()
@property (strong, nonatomic)UISwitch *switchBtn;
@end

@implementation TestController

- (void)viewDidLoad {
    [super viewDidLoad];
}

#pragma mark - lazyload
- (UISwitch *)switchBtn{
    if (!_switchBtn) {
        _switchBtn = [[UISwitch alloc]initWithFrame:CGRectMake(100, 100, 100, 100)];
        [self.view addSubview:_switchBtn];
        // 设置默认开关状态属性
        _switchBtn.on = YES;
        // animated 动画效果开关失效
        // [_switchBtn setOn:YES animated:YES];
        
        // 设置中间按钮(拇指)的颜色
        _switchBtn.thumbTintColor = [UIColor grayColor];
        
        // 设置on状态的背景色
        _switchBtn.onTintColor = [UIColor blueColor];
        
        // 是否隐藏
        // switchButton.hidden = YES;
        
        // masory布局
        [_switchBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.top.equalTo(self.view);
            make.size.mas_equalTo(CGSizeMake(50, 50));
        }];
        
        
        [_switchBtn bk_addEventHandler:^(id  _Nonnull sender) {
            self.view.backgroundColor = [(UISwitch *)sender isOn]?[UIColor redColor]:[UIColor greenColor];
        } forControlEvents:UIControlEventTouchUpInside];
    }
    return _switchBtn;
}
@end

你可能感兴趣的:(UIKit之UISwitch 开关)