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

iPhone How-to:如何更改UISwitch的提示文本

2011-07-18 12:54 537 查看
UISwitch(如下图)可以认为是其他UI库中Checkbox的替代品,但所呈现的内容更丰富,包括文本、颜色、动画。默认情况下,UISwitch的提示文本分别是ON和OFF,并很好地支持国际化以在不同区域语言下显示不同的文字,但由于无法定制导致在有些应用场景中显得不是很准确。比如在询问是否同意时希望提示文本可以是YES和NO,判断是否正确则应该是TRUE和FALSE等等。为此需要对UISwitch进行扩展。考虑到继承会导致控件继承关系太深,因此采用了Objective C的特性之一的Category。


实现的主要原理就是找到UISwitch中用于显示文本的UILabel控件并打标记以便在需要设定文本的时候访问到相应控件。Category声明:
@interface UISwitch (CustomText)

+ (UISwitch *) switchWithLeftText: (NSString *) tag1 andRight: (NSString *) tag2;
@property (nonatomic, readonly) UILabel *label1;
@property (nonatomic, readonly) UILabel *label2;

@end
Category实现:
#define TAG_OFFSET      900

@implementation UISwitch (CustomText)
- (void) locateAndTagAndTag: (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 locatelocateAndTagAndTag: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 locateAndTag:switchView withCount:&labelCount];
if (labelCount == 2)
{
[switchView.label1 setText:tag1];
[switchView.label2 setText:tag2];
}
return [switchView autorelease];
}

@end
在实际应用中,实例化定制的UISwitch的代码如下:
UISwitch *switch = [UISwitch switchWithLeftText:@"YES" andRight:@"NO"];
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: