UISwitch

133 阅读1分钟
#import "ViewController.h"

@interface ViewController ()

@property (nonatomic,strong) UISwitch *uiSwitch;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self.view addSubview:self.uiSwitch];
}

- (UISwitch *)uiSwitch {
    if (!_uiSwitch) {
        _uiSwitch = [[UISwitch alloc] init];
        _uiSwitch.frame = CGRectMake(100, 100, 0, 0);
        [_uiSwitch setOn:YES animated:YES];
        _uiSwitch.onTintColor = [[UIColor redColor] colorWithAlphaComponent:0.8]; //开关状态为开的时候左侧颜色
        _uiSwitch.tintColor = [UIColor yellowColor];  //开关状态为关的时候右侧边框颜色
        _uiSwitch.thumbTintColor = [[UIColor cyanColor] colorWithAlphaComponent:0.6]; //圆形按钮颜色
        [_uiSwitch addTarget:self action:@selector(switchAction:) forControlEvents:UIControlEventValueChanged];
        _uiSwitch.transform = CGAffineTransformMakeScale(0.5, 0.5);//缩放
        _uiSwitch.layer.cornerRadius = 3.5f;
        _uiSwitch.layer.masksToBounds = YES;
    }
    return _uiSwitch;
}

- (void)switchAction:(UISwitch *)uiSwitch {
    if (uiSwitch.on == YES) {
        NSLog(@"开");
    }else{
        NSLog(@"关");
    }
}

@end