UISwitch控件两种使用方法和监听

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

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

2、打开ViewController.m文件在viewDidLoad方法里添加代码:
- (void)viewDidLoad
{
[super viewDidLoad][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,方便显示效果

运行,效果:

[img]http://dl.iteye.com/upload/attachment/0078/6219/5b45183e-af3a-30e4-9b4f-31d0402fc08a.png[/img]


二、通过拖拽方法使用UISwitch

1、往xib文件上拖拽一个UISwitch控件。


[img]http://dl.iteye.com/upload/attachment/0078/6221/c65a47c4-9a1c-37de-91c1-9a5913caf4bb.png[/img]


2、按alt+command + return键开启Assistant Editor模式,选中UISwitch控件,按住Control键,往ViewController.h拖拽
[img]
[img]http://dl.iteye.com/upload/attachment/0078/6223/0c3b7d2d-624e-3e2d-af56-2eb3436040bc.png[/img]
[/img]

3、选Action方式
[img]
[img]http://dl.iteye.com/upload/attachment/0078/6225/d9c2d451-4d47-3582-8d3e-57b48f4c9eee.png[/img]
[/img]

4、.m文件中实现switchAction 。刚才动态创建的时候也用到这个方法名称,可以先注释掉刚才的。
- (IBAction)switchAction:(id)sender {
UISwitch *switchButton = (UISwitch*)sender;
BOOL isButtonOn = [switchButton isOn];
if (isButtonOn) {
showSwitchValue.text = @"是";
}else {
showSwitchValue.text = @"否";
}
}


运行就可以了。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值