系统自带的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. Oculus Rift, HTC Vive, SONY PSVR的全面对比

    http://blog.csdn.net/xoyojank/article/details/50927572 这次有幸参加了GDC 2016, 终于把三大设备体验了个遍, 也试玩了很多不错的VR游戏. ...

  2. Cordova 系列之Mac OS 环境配置

    1.从AppStore 安装xcode 2.安装node.js环境 http://nodejs.org/ 3.使用命令行安装 cordova 命令行帮助:http://cordova.apache.o ...

  3. cmd,bat和dos的区别

    区别 dos是磁盘操作系统(Disk Operating System),是个人计算机上的一类操作系统. bat是DOS命令,在任何dos环境下都可以使用. bat文件是dos下的批处理文件,批处理文 ...

  4. Tomcat - ClassFormatException的解决方法

    问题与分析 在使用Tomcat7运行web项目时报错如下: 严重: Compilation error org.eclipse.jdt.internal.compiler.classfmt.Class ...

  5. layui 单选框选中事件

    <div class="layui-form-item" pane=""> <label class="layui-form-lab ...

  6. java小游戏——猜数字

    import java.util.ArrayList; import java.util.List; import java.util.Random; public class Num01 { sta ...

  7. CentOS7下使用Docker容器化.net Core 2.2

    一.使用 yum 安装(CentOS 7下) Docker 要求 CentOS 系统的内核版本高于 3.10 ,查看本页面的前提条件来验证你的CentOS 版本是否支持 Docker . 通过 una ...

  8. elastcisearch中文分词器各个版本

    地址 https://github.com/medcl/elasticsearch-analysis-ik/releases?after=v6.0.1

  9. 访问NopCommerce的Admin 运行Nop.Admin后台管理

    Step 1.下载和安装NopCommerce的源码: Step 2.打开和运行Presentation下的Nop.Web 项目: Step 3.初次运行 会弹出界面 配置管理员账号 和 数据库信息: ...

  10. asp.net 图表

    感谢csdn深南大道,文章转自http://blog.csdn.net/smartsmile2012/article/details/17356673 前台代码 <div> <asp ...