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

 

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

Category声明:

 
  
  1. @interface UISwitch (CustomText)  
  2.  
  3. + (UISwitch *) switchWithLeftText: (NSString *) tag1 andRight: (NSString *) tag2;  
  4. @property (nonatomic, readonly) UILabel *label1;  
  5. @property (nonatomic, readonly) UILabel *label2;  
  6.  
  7. @end  

Category实现:

 
  
  1. #define TAG_OFFSET      900  
  2.  
  3. @implementation UISwitch (CustomText)  
  4. - (void) locateAndTagAndTag: (UIView *) aView withCount:(int *) count  
  5. {  
  6.         for (UIView *subview in [aView subviews])  
  7.         {  
  8.                 if ([subview isKindOfClass:[UILabel class]])  
  9.                 {  
  10.                         *count += 1;  
  11.                         [subview setTag:(TAG_OFFSET + *count)];  
  12.                 }  
  13.                 else  
  14.                         [self locatelocateAndTagAndTag:subview withCount:count];  
  15.         }  
  16. }  
  17.  
  18. - (UILabel *) label1  
  19. {  
  20.         return (UILabel *) [self viewWithTag:TAG_OFFSET + 1];  
  21. }  
  22.  
  23. - (UILabel *) label2  
  24. {  
  25.         return (UILabel *) [self viewWithTag:TAG_OFFSET + 2];  
  26. }  
  27.  
  28. + (UISwitch *) switchWithLeftText: (NSString *) tag1 andRight: (NSString *) tag2  
  29. {  
  30.         UISwitch *switchView = [[UISwitch alloc] initWithFrame:CGRectZero];  
  31.         int labelCount = 0;  
  32.         [switchView locateAndTag:switchView withCount:&labelCount];  
  33.         if (labelCount == 2)  
  34.         {  
  35.                 [switchView.label1 setText:tag1];  
  36.                 [switchView.label2 setText:tag2];  
  37.         }  
  38.         return [switchView autorelease];  
  39. }  
  40.  
  41. @end 

在实际应用中,实例化定制的UISwitch的代码如下:

 
  
  1. UISwitch *switch = [UISwitch switchWithLeftText:@"YES" andRight:@"NO"];