码迷,mamicode.com
首页 > 其他好文 > 详细

UISwitch开关控件

时间:2014-08-29 11:08:17      阅读:175      评论:0      收藏:0      [点我收藏+]

标签:uiswitch 开关控件 uilabl   label   

一、创建

 

  • 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的开关,在UILable上显示开,关状态

1.首先声明两个实例变量

@interface MHTViewController ()

{

    UILabel *_label;

    UISwitch *_switch;

}

@end


- (void)viewDidLoad

{

    [super viewDidLoad];

    // Do any additional setup after loading the view.

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

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

    //初始_label显示的文本

    _label.text = @"";

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

    _label.textAlignment = NSTextAlignmentCenter;

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

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

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

    _label.font = [UIFont systemFontOfSize:20];

    //设置文本的颜色

    _label.textColor = [UIColor blueColor];

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

    _label.numberOfLines = 0;

    //把对象加入到view

    [self.view addSubview:_label];

    //要记得把对象release

    [_label release];

    //创建一个UISwitch对象:_switch

    _switch = [[UISwitch alloc] init];

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

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

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

    _switch.on = NO;

    //把对象加入到view

    [self.view addSubview:_switch];

    //要记得把对象release

    [_switch release];

    //_switch绑定一个对象,当UIControEventValueChanged时会触发onChange:方法。

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

}



- (void)onChange:(id)sender

{

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

    UISwitch * tmpSwitch = (UISwitch *)sender;

    if (tmpSwitch.on) {

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

        _label.text = @"";  

    }else{

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

        _label.text = @"";

    }

}


UISwitch开关控件

标签:uiswitch 开关控件 uilabl   label   

原文地址:http://blog.csdn.net/mhtios/article/details/38919277

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!