iPhone How-to:如何更改UISwitch的提示文本
2011-12-11 08:11
260 查看
UISwitch(如下图)可以认为是其他UI库中Checkbox的替代品,但所呈现的内容更丰富,包括文本、颜色、动画。默认情况下,UISwitch的提示文本分别是ON和OFF,并很好地支持国际化以在不同区域语言下显示不同的文字,但由于无法定制导致在有些应用场景中显得不是很准确。比如在询问是否同意时希望提示文本可以是YES和NO,判断是否正确则应该是TRUE和FALSE等等。为此需要对UISwitch进行扩展。考虑到继承会导致控件继承关系太深,因此采用了Objective C的特性之一的Category。
![](http://hi.csdn.net/attachment/201107/18/0_13109649727OmN.gif)
实现的主要原理就是找到UISwitch中用于显示文本的UILabel控件并打标记以便在需要设定文本的时候访问到相应控件。
Category声明:
Category实现:
在实际应用中,实例化定制的UISwitch的代码如下:
![](http://hi.csdn.net/attachment/201107/18/0_13109649727OmN.gif)
实现的主要原理就是找到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"];
相关文章推荐
- iPhone How-to:如何更改UISwitch的提示文本 推荐
- iPhone How-to:如何更改UISwitch的提示文本
- iPhone How-to:如何更改UISwitch的提示文本
- iPhone How-to:如何更改UISwitch的提示文本
- [How to] 如何开始iphone的程序开发.
- Oracle HowTo:如何通过只读方式更改Oracle数据文件位置
- [HOW TO]如何在iPhone应用程序中发送邮件
- 如何关闭ReSharper中的[ Use 'var' ]提示How to Disable C# “var” Recommendation in ReSharper
- iPhone How-to:如何dump所有类
- How to get the password text in a text with password property from another process using C++ - 用C++如何从不同进程获取密码框文本
- iPhone How-to:如何发送邮件
- iPhone How-to:如何清除控件的Target-Action
- 【原创】SharePoint2010的SaveButton如何实现在跳转前给用户以提示[How to implement SaveButton display an alert when Redirect action]
- iPhone How-to:如何在NSDictionary中存放Selector
- iPhone How-to:如何移除发布版本中的NSLog输出
- Oracle HowTo:如何通过只读方式更改Oracle数据文件位置
- How to easily concatenate text based on criteria in Excel? 如何将Excel中的文本按条件合并
- iPhone How-to:如何调整UIView的Z-Order
- iPhone开发:如何阻止文件被iTunes和iCloud同步 How do I prevent files from being backed up to iCloud and iTunes?
- Oracle HowTo:如何使用Leading提示改变表连接方式