系统自带的UISwitch是这样的:

既不能写字,也不能改颜色,于是在网上找到了这么一个自定义的Switch按钮,具体出处找不见了。记录一下,怕以后找不见了。

先看下效果图:

按钮的样式很多,可以文字,可以写多行,文字大小和颜色都可以设置。

看下它的源码:

  1. #import <Foundation/Foundation.h>
  2. @interface HMCustomSwitch : UISlider {
  3. BOOL on;
  4. UIColor *tintColor;
  5. UIView *clippingView;
  6. UILabel *rightLabel;
  7. UILabel *leftLabel;
  8. // private member
  9. BOOL m_touchedSelf;
  10. }
  11. @property(nonatomic,getter=isOn) BOOL on;
  12. @property (nonatomic,retain) UIColor *tintColor;
  13. @property (nonatomic,retain) UIView *clippingView;
  14. @property (nonatomic,retain) UILabel *rightLabel;
  15. @property (nonatomic,retain) UILabel *leftLabel;
  16. + (HMCustomSwitch *) switchWithLeftText: (NSString *) tag1 andRight: (NSString *) tag2;
  17. - (void)setOn:(BOOL)on animated:(BOOL)animated;

.m文件

  1. #import "HMCustomSwitch.h"
  2. @implementation HMCustomSwitch
  3. @synthesize on;
  4. @synthesize tintColor, clippingView, leftLabel, rightLabel;
  5. +(HMCustomSwitch *)switchWithLeftText:(NSString *)leftText andRight:(NSString *)rightText
  6. {
  7. HMCustomSwitch *switchView = [[HMCustomSwitch alloc] initWithFrame:CGRectZero];
  8. switchView.leftLabel.text = leftText;
  9. switchView.rightLabel.text = rightText;
  10. return [switchView autorelease];
  11. }
  12. -(id)initWithFrame:(CGRect)rect
  13. {
  14. if ((self=[super initWithFrame:CGRectMake(rect.origin.x,rect.origin.y,95,27)]))
  15. {
  16. //      self.clipsToBounds = YES;
  17. [self awakeFromNib];        // do all setup in awakeFromNib so that control can be created manually or in a nib file
  18. }
  19. return self;
  20. }
  21. -(void)awakeFromNib
  22. {
  23. [super awakeFromNib];
  24. self.backgroundColor = [UIColor clearColor];
  25. [self setThumbImage:[UIImage imageNamed:@"switchThumb.png"] forState:UIControlStateNormal];
  26. [self setMinimumTrackImage:[UIImage imageNamed:@"switchBlueBg.png"] forState:UIControlStateNormal];
  27. [self setMaximumTrackImage:[UIImage imageNamed:@"switchOffPlain.png"] forState:UIControlStateNormal];
  28. self.minimumValue = 0;
  29. self.maximumValue = 1;
  30. self.continuous = NO;
  31. self.on = NO;
  32. self.value = 0.0;
  33. self.clippingView = [[UIView alloc] initWithFrame:CGRectMake(4,2,87,23)];
  34. self.clippingView.clipsToBounds = YES;
  35. self.clippingView.userInteractionEnabled = NO;
  36. self.clippingView.backgroundColor = [UIColor clearColor];
  37. [self addSubview:self.clippingView];
  38. [self.clippingView release];
  39. NSString *leftLabelText = NSLocalizedString(@"ON","Custom UISwitch ON label. If localized to empty string then I/O will be used");
  40. if ([leftLabelText length] == 0)
  41. {
  42. leftLabelText = @"l";       // use helvetica lowercase L to be a 1.
  43. }
  44. self.leftLabel = [[UILabel alloc] init];
  45. self.leftLabel.frame = CGRectMake(0, 0, 48, 23);
  46. self.leftLabel.text = leftLabelText;
  47. self.leftLabel.textAlignment = NSTextAlignmentCenter;
  48. self.leftLabel.font = [UIFont boldSystemFontOfSize:17];
  49. self.leftLabel.textColor = [UIColor whiteColor];
  50. self.leftLabel.backgroundColor = [UIColor clearColor];
  51. //      self.leftLabel.shadowColor = [UIColor redColor];
  52. //      self.leftLabel.shadowOffset = CGSizeMake(0,0);
  53. [self.clippingView addSubview:self.leftLabel];
  54. [self.leftLabel release];
  55. NSString *rightLabelText = NSLocalizedString(@"OFF","Custom UISwitch OFF label. If localized to empty string then I/O will be used");
  56. if ([rightLabelText length] == 0)
  57. {
  58. rightLabelText = @"O";  // use helvetica uppercase o to be a 0.
  59. }
  60. self.rightLabel = [[UILabel alloc] init];
  61. self.rightLabel.frame = CGRectMake(95, 0, 48, 23);
  62. self.rightLabel.text = rightLabelText;
  63. self.rightLabel.textAlignment = NSTextAlignmentCenter;
  64. self.rightLabel.font = [UIFont boldSystemFontOfSize:17];
  65. self.rightLabel.textColor = [UIColor grayColor];
  66. self.rightLabel.backgroundColor = [UIColor clearColor];
  67. //      self.rightLabel.shadowColor = [UIColor redColor];
  68. //      self.rightLabel.shadowOffset = CGSizeMake(0,0);
  69. [self.clippingView addSubview:self.rightLabel];
  70. [self.rightLabel release];
  71. }
  72. -(void)layoutSubviews
  73. {
  74. [super layoutSubviews];
  75. //  NSLog(@"leftLabel=%@",NSStringFromCGRect(self.leftLabel.frame));
  76. // move the labels to the front
  77. [self.clippingView removeFromSuperview];
  78. [self addSubview:self.clippingView];
  79. CGFloat thumbWidth = self.currentThumbImage.size.width;
  80. CGFloat switchWidth = self.bounds.size.width;
  81. CGFloat labelWidth = switchWidth - thumbWidth;
  82. CGFloat inset = self.clippingView.frame.origin.x;
  83. //  NSInteger xPos = self.value * (self.bounds.size.width - thumbWidth) - (self.leftLabel.frame.size.width - thumbWidth/2);
  84. NSInteger xPos = self.value * labelWidth - labelWidth - inset;
  85. self.leftLabel.frame = CGRectMake(xPos, 0, labelWidth, 23);
  86. //  xPos = self.value * (self.bounds.size.width - thumbWidth) + (self.rightLabel.frame.size.width - thumbWidth/2);
  87. xPos = switchWidth + (self.value * labelWidth - labelWidth) - inset;
  88. self.rightLabel.frame = CGRectMake(xPos, 0, labelWidth, 23);
  89. //  NSLog(@"value=%f    xPos=%i",self.value,xPos);
  90. //  NSLog(@"thumbWidth=%f    self.bounds.size.width=%f",thumbWidth,self.bounds.size.width);
  91. }
  92. - (UIImage *)image:(UIImage*)image tintedWithColor:(UIColor *)tint
  93. {
  94. if (tint != nil)
  95. {
  96. UIGraphicsBeginImageContext(image.size);
  97. //draw mask so the alpha is respected
  98. CGContextRef currentContext = UIGraphicsGetCurrentContext();
  99. CGImageRef maskImage = [image CGImage];
  100. CGContextClipToMask(currentContext, CGRectMake(0, 0, image.size.width, image.size.height), maskImage);
  101. CGContextDrawImage(currentContext, CGRectMake(0,0, image.size.width, image.size.height), image.CGImage);
  102. [image drawAtPoint:CGPointMake(0,0)];
  103. [tint setFill];
  104. UIRectFillUsingBlendMode(CGRectMake(0,0,image.size.width,image.size.height),kCGBlendModeColor);
  105. UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
  106. UIGraphicsEndImageContext();
  107. return newImage;
  108. }
  109. else
  110. {
  111. return image;
  112. }
  113. }
  114. -(void)setTintColor:(UIColor*)color
  115. {
  116. if (color != tintColor)
  117. {
  118. [tintColor release];
  119. tintColor = [color retain];
  120. [self setMinimumTrackImage:[self image:[UIImage imageNamed:@"switchBlueBg.png"] tintedWithColor:tintColor] forState:UIControlStateNormal];
  121. }
  122. }
  123. - (void)setOn:(BOOL)turnOn animated:(BOOL)animated;
  124. {
  125. on = turnOn;
  126. if (animated)
  127. {
  128. [UIView  beginAnimations:nil context:nil];
  129. [UIView setAnimationDuration:0.2];
  130. }
  131. if (on)
  132. {
  133. self.value = 1.0;
  134. }
  135. else
  136. {
  137. self.value = 0.0;
  138. }
  139. if (animated)
  140. {
  141. [UIView commitAnimations];
  142. }
  143. }
  144. - (void)setOn:(BOOL)turnOn
  145. {
  146. [self setOn:turnOn animated:NO];
  147. }
  148. - (void)endTrackingWithTouch:(UITouch *)touch withEvent:(UIEvent *)event
  149. {
  150. NSLog(@"preendTrackingWithtouch");
  151. [super endTrackingWithTouch:touch withEvent:event];
  152. NSLog(@"postendTrackingWithtouch");
  153. m_touchedSelf = YES;
  154. [self setOn:on animated:YES];
  155. }
  156. - (void)touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event
  157. {
  158. [super touchesBegan:touches withEvent:event];
  159. NSLog(@"touchesBegan");
  160. m_touchedSelf = NO;
  161. on = !on;
  162. }
  163. - (void)touchesEnded:(NSSet*)touches withEvent:(UIEvent*)event
  164. {
  165. [super touchesEnded:touches withEvent:event];
  166. NSLog(@"touchesEnded");
  167. if (!m_touchedSelf)
  168. {
  169. [self setOn:on animated:YES];
  170. [self sendActionsForControlEvents:UIControlEventValueChanged];
  171. }
  172. }
  173. -(void)dealloc
  174. {
  175. [tintColor release];
  176. [clippingView release];
  177. [rightLabel release];
  178. [leftLabel release];
  179. [super dealloc];
  180. }
  181. @end

看代码可以知道,其实它是通过继承UISlider控件实现的,UISlider的左右分别是个UILabel,当YES的时候,滑块滑到了最右边,NO的时候滑到了最左边。

如何在代码中使用它呢?很简单:

  1. - (void)loadView
  2. {
  3. UIView *contentView = [[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]];
  4. self.view = contentView;
  5. contentView.backgroundColor = [UIColor whiteColor];
  6. // Standard ON/OFF
  7. HMCustomSwitch *switchView = [[HMCustomSwitch alloc] initWithFrame:CGRectZero];
  8. switchView.center = CGPointMake(160.0f, 20.0f);
  9. switchView.on = YES;
  10. [contentView addSubview:switchView];
  11. [switchView release];
  12. // Custom YES/NO
  13. switchView = [HMCustomSwitch switchWithLeftText:@"YES" andRight:@"NO"];
  14. switchView.center = CGPointMake(160.0f, 60.0f);
  15. switchView.on = YES;
  16. [contentView addSubview:switchView];
  17. // Custom font and color
  18. switchView = [HMCustomSwitch switchWithLeftText:@"Hello " andRight:@"ABC "];
  19. switchView.center = CGPointMake(160.0f, 100.0f);
  20. switchView.on = YES;
  21. [switchView.leftLabel setFont:[UIFont boldSystemFontOfSize:13.0f]];
  22. [switchView.rightLabel setFont:[UIFont italicSystemFontOfSize:15.0f]];
  23. [switchView.rightLabel setTextColor:[UIColor blueColor]];
  24. [contentView addSubview:switchView];
  25. // Multiple lines
  26. switchView = [HMCustomSwitch switchWithLeftText:@"Hello\nWorld" andRight:@"Bye\nWorld"];
  27. switchView.center = CGPointMake(160.0f, 140.0f);
  28. switchView.on = YES;
  29. switchView.tintColor = [UIColor orangeColor];
  30. switchView.leftLabel.font = [UIFont boldSystemFontOfSize:9.0f];
  31. switchView.rightLabel.font = [UIFont boldSystemFontOfSize:9.0f];
  32. switchView.leftLabel.numberOfLines = 2;
  33. switchView.rightLabel.numberOfLines = 2;
  34. switchView.leftLabel.lineBreakMode = NSLineBreakByWordWrapping;
  35. switchView.rightLabel.lineBreakMode = NSLineBreakByWordWrapping;
  36. [contentView addSubview:switchView];
  37. switchView = [[HMCustomSwitch alloc] init];
  38. switchView.center = CGPointMake(160.0f, 180.0f);
  39. switchView.on = YES;
  40. switchView.tintColor = [UIColor purpleColor];
  41. [contentView addSubview:switchView];
  42. [switchView release];
  43. switchView = [HMCustomSwitch switchWithLeftText:@"l" andRight:@"O"];
  44. switchView.center = CGPointMake(160.0f, 220.0f);
  45. //  customSwitch.tintColor = [UIColor colorWithRed:125.f/255.f green:157.f/255.f blue:93.f/255.f alpha:1.0];
  46. //  customSwitch.tintColor = [UIColor colorWithRed:125.f/255.f green:157.f/255.f blue:93.f/255.f alpha:1.0];
  47. [contentView addSubview:switchView];
  48. // Standard ON/OFF
  49. switchView = [[HMCustomSwitch alloc] init];
  50. switchView.center = CGPointMake(160.0f, 260.0f);
  51. switchView.tintColor = [UIColor colorWithRed:125.f/255.f green:157.f/255.f blue:93.f/255.f alpha:1.0];
  52. [switchView addTarget:self action:@selector(switchFlipped:) forControlEvents:UIControlEventValueChanged];
  53. [contentView addSubview:switchView];
  54. [switchView release];
  55. UIToolbar *toolbar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 420, 320, 40)];
  56. toolbar.tintColor = [UIColor colorWithRed:125.f/255.f green:157.f/255.f blue:93.f/255.f alpha:1.0];
  57. [contentView addSubview:toolbar];
  58. [contentView release];
  59. }
  60. -(void)switchFlipped:(HMCustomSwitch*)switchView
  61. {
  62. NSLog(@"switchFlipped=%f  on:%@",switchView.value, (switchView.on?@"Y":@"N"));
  63. }

代码下载地址:https://github.com/schelling/HMCustomSwitch

ios之自定义UISwitch的更多相关文章

  1. 1.2UISwitch 1.3 自定义UIswitch 1.4pickerView

    1.2 UISwitch创建和使用开关 问题你想给你的用户打开一个选项或关闭的能力.解使用UISwitch类. 讨论该UISwitch类提供像在图1-7为自动大写,自动校正,等等所示的开/ ...

  2. iOS 如何自定义UISearchBar 中textField的高度

    iOS 如何自定义UISearchBar 中textField的高度 只需设置下边的方法就可以 [_searchBar setSearchFieldBackgroundImage:[UIImage i ...

  3. iOS 隐藏自定义tabbar

    iOS  隐藏自定义tabbar -(void)viewWillAppear:(BOOL)animated { NSArray *array=self.tabBarController.view.su ...

  4. ios 实现自定义状态栏StatusBar 和 导航栏navigationBar 的状态和颜色

    很多app中可以看到不同与导航栏的状态栏的颜色,他妈的真绕嘴. 一.更改状态栏颜色 (StatusBar) 就是比如导航栏是红色的状态栏是绿色的. 要实现这样的效果其实很简单,就是添加一个背景view ...

  5. ios UIWebView自定义Alert风格的弹框

    之前开发过一个App,因为公司之前写好了网页版的内容和安卓版本的App,我进去后老板要求我ios直接用网页的内容,而不需要自己再搭建框架.我一听,偷笑了,这不就是一个UIWebView吗?简单! 但是 ...

  6. 【IOS】自定义可点击的多文本跑马灯YFRollingLabel

    需求 项目中需要用到跑马灯来仅展示一条消息,长度合适则不滚动,过长则循环滚动. 虽然不是我写的,但看了看代码,是在一个UIView里面放入两个UILabel, 在前一个快结束的时候,另一个显示.然而点 ...

  7. iOS - 使用自定义字体-苹方字体

    苹方提供了六个字重,font-family 定义如下:苹方-简 常规体font-family: PingFangSC-Regular, sans-serif;苹方-简 极细体font-family: ...

  8. [IOS]swift自定义uicollectionviewcell

    刚刚接触swift以及ios,不是很理解有的逻辑,导致某些问题.这里分享一下swift自定义uicollectionviewcell 首先我的viewcontroller不是直接继承uicollect ...

  9. ios中自定义tableView,CollectionView的cell什么时候用nib加载,什么时候用标识重用

    做了一段时间的iOS,在菜鸟的路上还有很长的路要走,把遇到的问题记下来,好记性不如烂笔头. 在项目开发中大家经常会用到tableView和collectionView两个控件,然而在cell的自定义上 ...

随机推荐

  1. Html5shiv ---- 让IE低版本浏览器识别并支持HTML5标签

    Html5shiv.js是针对IE浏览器的 javaScript 补丁,作用如题 该脚本的下载链接 使用使在head标签中使用script标签引用即可

  2. Eclipse - 安装了jd-eclipse插件后依然无法反编译类文件

    问题 Eclipse在安装了jd-eclipse插件后依然无法反编译类文件,这个问题是因为没有修改默认的类文件查看器. 解决方法 修改默认的类文件查看器为jd-eclipse Window -> ...

  3. SOA思想

    参考:https://www.cnblogs.com/renzhitian/p/6853289.html 是什么 SOA service-oriented architecture 面向服务的体系结构 ...

  4. python 基础(七) 异常处理

    异常处理 一.需求 当遇到错误的时候 不让程序停止执行 而是越过错误继续执行 二.主体结构 (抓取所有异常) try:   可能出现异常的代码段 except:   出现异常以后的处理   三.处理特 ...

  5. hdu2586 LCA带边权的Targan算法

    bryce1010模板 http://acm.hdu.edu.cn/showproblem.php?pid=2586 #include<bits/stdc++.h> using names ...

  6. python入门之迭代器

    迭代器 已知,可以直接作用于for循环的数据类型有: 一类是集合数据类型,如list.tuple.dict.set.str 一类是generator,包括生成器和带yield的generator fu ...

  7. JDBC事务之例子篇

    上一篇随笔记了一些有关JDBC事务管理的理论知识.这篇来看例子(主要怕一篇随笔装所有东西太长了然后分开呵呵) 一般讲事务管理的,都是拿转钱来当例子的,嗯没错我们这也是. 这个是数据库中的t_accou ...

  8. SDIO学习

    https://baijiahao.baidu.com/s?id=1561100856106707&wfr=spider&for=pc http://www.eepw.com.cn/a ...

  9. csu 1552: Friends 二分图 + Miller_Rabin

    http://acm.csu.edu.cn/csuoj/problemset/problem?pid=1552 把那n个数写两次,分成相同的两堆,判断相加是质数的,连一条边,然后找最大匹配,ans = ...

  10. 第六章 设计程序架构 之 设计实现WebSocket策略

    1. 概述 传统网页的通信方式是请求-响应模式,每次请求-响应都是新的连接.连接的建立和断开也是需要消耗资源的. WebSocket是基于TCP协议,实现单个连接上的双向通信. 本章内容包括: 异步读 ...