温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

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

发布时间:2020-06-15 09:27:02 阅读:7652 作者:benjielin 栏目:开发技术
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

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

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

实现的主要原理就是找到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"]; 

亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI

开发者交流群×