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

ios的UISwitch

2014-09-18 20:27 225 查看
正如分段控件代替了单选按钮,开关也代替了点选框。开关是到目前为止用起来最简单的控件,不过仍然可以作一定程度的定制化。

一、创建

[java] view plaincopyprint?

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

是不是很奇怪,大小竟然是0.0×0.0,没错,系统会自动帮你决定最佳的尺寸,你自己写的尺寸会被忽略掉,你只要定义好相对父视图的位置就好了。关于纯代码创建控件请参看我的另一篇博文:《有关View的几个基础知识点》

二、显示控件

[java] view plaincopyprint?

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



[java] view plaincopyprint?

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

二、开关状态

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

[java] view plaincopyprint?

BOOL switchStatus = mySwitch.on;

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

[java] view plaincopyprint?

[ mySwitch setOn:YES animated:YES];

三、通知

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

[java] view plaincopyprint?

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

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

[java] view plaincopyprint?

- (void) switchValueChanged:(id)sender{

UISwitch* control = (UISwitch*)sender;

if(control == mySwitch){

BOOL on = control.on;

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

}

}

了解了开关之后是不是觉得很棒呢?是不是发现有好多地方可以用到它?觉得不错就马上写点代码体验一下吧!


iphone
自定义UISwitch

修改UISwitch的标题,实现自定义UISwitch方法有两种:

1.使用类别扩展UISwitch。

如下:

下面是UISwitch.h文件:

#import

@interface UISwitch (tagged)

+ (UISwitch *) switchWithLeftText: (NSString *)
tag1 andRight: (NSString *) tag2;

@property (nonatomic, readonly) UILabel
*label1;

@property (nonatomic, readonly) UILabel
*label2;

@end

UISwitch.m文件:

#import "UISwitch-Extended.h"

#define TAG_OFFSET 900

@implementation UISwitch (tagged)

- (void) spelunkAndTag: (UIView *) aView withCount:(int *)
count

{

for (UIView *subview in [aView subviews])

{

if ([subview isKindOfClass:[UILabel class]])

{

*count += 1;

[subview setTag:(TAG_OFFSET +
*count)];

}

else

[self spelunkAndTag:subview withCount:count];

}

}

- (UILabel *) label1

{

return (UILabel *)
[self viewWithTag:TAG_OFFSET + 1];

}

- (UILabel *) label2

{

return (UILabel *) [self viewWithTag:TAG_OFFSET + 2];

}

+ (UISwitch *) switchWithLeftText: (NSString *)
tag1 andRight: (NSString *) tag2

{

UISwitch *switchView = [[UISwitch alloc] initWithFrame:CGRectZero];

int labelCount = 0;

[switchView spelunkAndTag:switchView withCount:&labelCount];

if (labelCount == 2)

{

[switchView.label1 setText:tag1];

[switchView.label2 setText:tag2];

}

return [switchView autorelease];

}

@end

2.还有一种方法,这种方法比较简单,但比较难懂,我不甚理解。

UISwitch *isFooOrBar=[[UISwitch alloc] init];

((UILabel *)[[[[[[isFooOrBar subviews] lastObject] subviews] objectAtIndex:2] subviews]objectAtIndex:0]).text = @"Foo";

((UILabel *)[[[[[[isFooOrBar subviews] lastObject] subviews] objectAtIndex:2] subviews]objectAtIndex:1]).text = @"Bar";
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: