iOS开发--UISwitch用法

原文地址:iOS开发--UISwitch用法 作者:追逐梦想

1.UISwitch的初始化

 

1 UISwitch *switchView = [[UISwitch alloc] initWithFrame:CGRectMake(4.0f, 16.0f, 100.0f, 28.0f)];

 

2.设置UISwitch的初始化状态

 

1 switchView.on = YES;//设置初始为ON的一边

 

3.UISwitch事件的响应

 

1 [switchView addTarget:self action:@selector(switchAction:) forControlEvents:UIControlEventValueChanged];

-(void) switchAction:(id)sender
      UISwitch * switch = (UISwitch *)sender;
}

另个版本:

.h文件中声明:

UISwitch * leftSwitch;


@property (nonatomic retainIBOutlet UISwitch * leftSwitch;


.m文件中添加:

@synthesize leftSwitch;



viewDidUnload()中添加:

leftSwitch nil;


dealloc()中添加:

[leftSwitch release];


显示

leftSwitch.hidden NO;


隐藏:

leftSwitch.hidden YES;


通过IBAction方法设置开关

-(IBAction) switchChanged:(id)sender

{

UISwitch * whichSwitch = (UISwitch *)sender;

BOOL setting = whichSwitch.isOn;

[leftSwitch setOn:setting animated:YES];

[rightSwitch setOn:setting animated:YES];

}


iphone 自定义UISwitch

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

1.使用类别扩展UISwitch。 

如下:

 下面是UISwitch.h文件:

 

#import <UIKit/UIKit.h>

 

@interface UISwitch (tagged)

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

@property (nonatomicreadonly) UILabel *label1;

@property (nonatomicreadonly) 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 allocinitWithFrame: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 allocinit];

 

 

 


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

((UILabel *)[[[[[[isFooOrBar subviewslastObjectsubviewsobjectAtIndex:2subviews]objectAtIndex:1]).text @"Bar";

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值