复制代码
#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";*
四、一些常用方法
获得开关状态
复制代码
BOOL setting = switchView.isOn;
NSLog(@"%d",setting);
设置开关状态 NO关闭状态,YES打开状态
复制代码
[switchView setOn:setting animated:YES];
设置开光的切换
复制代码
switchView.onTintColor = [UIColor orangeColor];
设置按钮的颜色
复制代码
switchView.thumbTintColor = [UIColor redColor];
开关控件边框的颜色










