正如分段控件代替了单选按钮,开关也代替了点选框。开关是到目前为止用起来最简单的控件,不过仍然可以作一定程度的定制化。
一、创建
- UISwitch*
mySwitch = [[ UISwitch alloc]initWithFrame:CGRectMake(200.0,10.0,0.0,0.0)];
二、显示控件
- [
parrentView addSubview:mySwitch];//添加到父视图
- self.navigationItem.titleView
= mySwitch;//添加到导航栏
开关状态可以通过它的on属性读取,这个属性是一个BOOL值,表示开关是否被打开:
- BOOL
switchStatus = mySwitch.on;
- [
mySwitch setOn:YES animated:YES];
三、通知
想要在开关状态切换时收到通知,可以用UIControl类的addTarget方法为UIControlEventValueChang
- [
mySwitch addTarget: self action:@selector(switchValueChanged:) forControlEvents:UIControlEventValueChang ed];
- -
(void) switchValueChanged:(id)sender{ -
UISwitch* control = (UISwitch*)sender; -
if(control == mySwitch){ -
BOOL on = control.on; -
//添加自己要处理的事情代码 -
} - }
了解了开关之后是不是觉得很棒呢?是不是发现有好多地方可以用到它?觉得不错就马上写点代码体验一下吧!
iphone 自定义UISwitch
修改UISwitch的标题,实现自定义UISwitch方法有两种:
1.使用类别扩展UISwitch。
如下:
#import
@interface
+ (UISwitch
@property
@property
@end
UISwitch.m文件:
#import
#define TAG_OFFSET
@implementation
- (void) spelunkAndTag: (UIView
{
}
- (UILabel
{
}
- (UILabel
{
return
}
+ (UISwitch
{
int
[switchView
if
{
[switchView.label1
[switchView.label2
}
return
}
@end
2.还有一种方法,这种方法比较简单,但比较难懂,我不甚理解。
UISwitch
((UILabel
((UILabel