详解iOS App中UISwitch开关组件的基本创建及使用方法

2020-01-15 14:33:22王振洲
UISwitch组件就是我们平时在iOS设置菜单中开到的那种左右滑动的开关按钮,当然我们在开发时可以进行更多的自定义,这里我们就来详解iOS App中UISwitch开关组件的基本创建及使用方法  

一、第一种创建UISwitch组件的方法,在代码中动态创建。

1、打开Xcode, 新建项目Switch,选择Single View Application。

2、打开ViewController.m文件在viewDidLoad方法里添加代码:

复制代码
(void)viewDidLoad  
{  
    [super viewDidLoad];  
    UISwitch *switchButton = [[UISwitch alloc] initWithFrame:CGRectMake(50, 100, 20, 10)];  
    [switchButton setOn:YES];  
    [switchButton addTarget:self action:@selector(switchAction:) forControlEvents:UIControlEventValueChanged];  
    [self.view addSubview:switchButton]; 

 

    // Do any additional setup after loading the view, typically from a nib.  
}  
[switchButton addTarget:selfaction:@selector(switchAction:)forControlEvents:UIControlEventValueChanged];


代码中selector中的switchAction:需要我们自己实现,就是按下时接收到的事件。

 

记得把switchButton加到当前view,调用[self.viewaddSubview:switchButton];

3、监听UISwitch按下事件

实现代码如下:

复制代码
(void)switchAction:(id)sender  
{  
    UISwitch *switchButton = (UISwitch*)sender;  
    BOOL isButtonOn = [switchButton isOn];  
    if (isButtonOn) {  
        showSwitchValue.text = @"是";  
    }else {  
        showSwitchValue.text = @"否";  
    }  

showSwitchValue是我通过拖拽控件方法放到界面上的Label,方便显示效果

 

运行,效果:

iOS,App,UISwitch