系统自带的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. Unity NGUI学习

    环境 Unity4.3    NGUI v3.68 导入 Project界面->右键->import package->custom package载入安装包即可 untiy4.6用 ...

  2. IT兄弟连 JavaWeb教程 Servlet会话跟踪 Cookie技术原理

    Cookie使用HTTPHeader传递数据.Cookie机制定义了两种报头,Set-Cookie报头和Cookie报头.Set-Cookie报头包含于Web服务器的响应头(ResponseHeade ...

  3. 【NOI省选模拟】小奇的花园

    「题目背景」 小奇在家中的花园漫步时,总是会思考一些奇怪的问题. 「问题描述」 小奇的花园有n个温室,标号为1到n,温室以及以及温室间的双向道路形成一棵树. 每个温室都种植着一种花,随着季节的变换,温 ...

  4. 最简大数据Spark-2.1.0

    0.0 前言 本文主要基于最新的Spark 2.1.0版本.阅读本文可以对Spark 2.1.0的学习过程,运行流程,关键组件,原理有所了解.文章有点长,你也可以直接阅读感兴趣的部分,但是还是建议全面 ...

  5. PostgreSQL - 模糊查询

    前言 like.not like在SQL中用于模糊查询,%表示任意个字符,_表示单个任意字符,如果需要在模糊查询中查询这两个通配符,需要用ESCAPE进行转义,如下: select * from ta ...

  6. pwnhub 相对路径覆盖

    这个pwnhub小m师傅的题,做的时候完全没有思路. 首先是注册然后可以看到一个加载css的地方,是相对路径加载(当然我并没有觉得有什么问题). 服务端和浏览器解析URL是有区别的,就是%2f 服务器 ...

  7. Qt 2D绘图之六:图形视图框架的事件处理与传播

    一.简介 图形视图框架中的事件都是首先由视图进行接收,然后传递给场景,再由场景传递给相应的图形项.而对于键盘事件,它会传递给获得焦点的图形项,可以使用QGraphicsScene类的setFocusI ...

  8. Codeforces Round #390 (Div. 2) D

    All our characters have hobbies. The same is true for Fedor. He enjoys shopping in the neighboring s ...

  9. centos 6.x下pxe+tftp+http+kickstart无人值守安装操作系统

    1.1 什么是PXE PXE(Pre-boot Execution Environment,预启动执行环境)是由Intel公司开发的最新技术,工作于Client/Server的网络模式,支持工作站通过 ...

  10. 安卓,IOS真机调试

    移动端前端开发真机调试攻略 有线调试: 一.IOS 移动端 (Safari开发者工具) 手机端:设置 → Safari → 高级 → Web 检查器 → 开. mac端:Safari → 偏好设置 → ...