您的位置:首页 > 产品设计 > UI/UE

UISwitch开关控件

2015-06-26 16:44 267 查看
一、创建

UISwitch* mySwitch = [[
UISwitch
alloc]initWithFrame:CGRectMake(200.0,10.0,0.0,0.0)];

是不是很奇怪,大小竟然是0.0×0.0,没错,系统会自动帮你决定最佳的尺寸,你自己写的尺寸会被忽略掉,你只要定义好相对父视图的位置就好了。默认尺寸为79 * 27。

二、显示控件

[ parrentView addSubview:mySwitch];//添加到父视图



self.navigationItem.titleView = mySwitch;//添加到导航栏

三、开关状态

开关状态可以通过它的on属性读取,这个属性是一个BOOL值,表示开关是否被打开:

BOOL switchStatus = mySwitch.on;

你可以在你的代码中用setOn方法来打开或关闭开关:

[ mySwitch setOn:YES animated:YES];

四、通知想要在开关状态切换时收到通知可以用UIControl类的addTarget方法为UIControlEventValueChanged事件添加一个动作。

[ mySwitch addTarget: self action:@selector(switchValueChanged:) forControlEvents:UIControlEventValueChanged];

这样,只要开关一被切换目标类(上例中目标类就是当前控制器self)就会调用switchValueChanged方法,

- (void) switchValueChanged:(id)sender{

UISwitch* control = (UISwitch*)sender;

if(control == mySwitch){

BOOL on = control.on;

//添加自己要处理的事情代码

}

}

五,代码示例

4.09UISwitch(2)

- (void)onChange:(id)sender

{

UISwitch * tmpSwitch = (UISwitch *)sender;

//强制转换sender的类型,sender代表发送者

if (tmpSwitch.on) {

_label.text =@"开";

//如果它的状态为On的话,_label显示的文本为“开”

}else{

_label.text =@"关";

//如果它的状态为Off的话,_label显示的文本为“关”

}

}

- (void)viewDidLoad

{

[super viewDidLoad];

_label = [[UILabelalloc]
initWithFrame:CGRectMake(0,20,
320, 50)];

//创建一个UILabel对象:_label;

_label.text =@"";

//初始_label显示的文本

_label.textAlignment =UITextAlignmentCenter;

//设置_label文本的对齐方式,默认为左对齐

_label.font = [UIFontfontWithName:@"Arial"size:50];

//设置文本的字体和大小

_label.font = [UIFontsystemFontOfSize:20];

//单纯的设置文本的大小

_label.textColor = [UIColorblueColor];

//设置文本的颜色

_label.numberOfLines =0;

//设置显示的行数,如果为0,则会自动扩充

[self.viewaddSubview:_label];

//把对象加入到view上

[_label release];

//要记得把对象release

_switch = [[UISwitchalloc]
init];

//创建一个UISwitch对象:_switch

_switch.frame =CGRectMake(120,100,
0, 0);

//设置它的位置,它的大小为79 * 27,不能改动

_switch.on =NO;

//设置它的初始状态为Off,

[self.viewaddSubview:_switch];

//把对象加入到view

[_switch release];

//要记得把对象release

[_switch addTarget:selfaction:@selector(onChange:)forControlEvents:UIControlEventValueChanged];

//给_switch绑定一个对象,当UIControEventValueChanged时会触发onChange:函数。

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: