UISwitch - 开关按钮 的使用详解

https://blog.csdn.net/catstarxcode/article/details/53541048#

//
//  ViewController.m
//  UISwitch滑块切换开关
//
//  Created by Liu,Wenbo(TBRD) on 2020/5/28.
//  Copyright © 2020 Liu,Wenbo(TBRD). All rights reserved.
//

#import "ViewController.h"

@interface ViewController ()
{
    UISwitch *switchButton;
}
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    //初始化UISwitch滑块
    switchButton = [[UISwitch alloc] initWithFrame:CGRectMake(100, 100, 100, 100)];
    
    //设置滑块的背景颜色
    //switchButton.backgroundColor = [UIColor orangeColor];

    //设置按钮开启的颜色 图片
    switchButton.onTintColor = [UIColor greenColor];
    //switchButton.onImage = [UIImage imageNamed:@""];//已弃用


    //设置关闭颜色 图片
    switchButton.tintColor = [UIColor redColor];
    //switchButton.offImage = [UIImage imageNamed:@""];//已弃用

    //设置中心按钮的颜色
    //switchButton.thumbTintColor = [UIColor purpleColor];
    
    //设置开关
    //switchButton.on = YES;
    
    
#pragma  mark - 添加点击事件
    [switchButton addTarget:self action:@selector(action:) forControlEvents:UIControlEventValueChanged];// UIControlEventValueChanged值是否改变
    
    //添加到视图
    [self.view addSubview:switchButton];
    
}
//点击事件处理方法
-(void)action:(UISwitch *)uiswitch{
    NSLog(@"开关是否开启:%d",uiswitch.isOn);//
}
//点击空白处的事件
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [switchButton setOn:!switchButton.on animated:YES];
}

@end

你可能感兴趣的:(IOS开发)