UISwitch开关控件

开关代替了点选框。开关是到目前为止用起来最简单的控件,不过仍然可以作一定程度的定制化。

一、创建

  1. UISwitch* mySwitch = [[ UISwitchalloc]initWithFrame:CGRectMake(200.0,10.0,0.0,0.0)];

是不是很奇怪,大小竟然是0.0×0.0,没错,系统会自动帮你决定最佳的尺寸,你自己写的尺寸会被忽略掉,你只要定义好相对父视图的位置就好了。默认尺寸为79 * 27。

二、显示控件

  1. [ parrentView addSubview:mySwitch];//添加到父视图

  1. self.navigationItem.titleView = mySwitch;//添加到导航栏

三、开关状态

开关状态可以通过它的on属性读取,这个属性是一个BOOL值,表示开关是否被打开:

  1. BOOL switchStatus = mySwitch.on;

你可以在你的代码中用setOn方法来打开或关闭开关:

  1. [ mySwitch setOn:YES animated:YES];

四、通知想要在开关状态切换时收到通知可以用UIControl类的addTarget方法为UIControlEventValueChanged事件添加一个动作。

  1. [ mySwitch addTarget: self action:@selector(switchValueChanged:) forControlEvents:UIControlEventValueChanged];

这样,只要开关一被切换目标类(上例中目标类就是当前控制器self)就会调用switchValueChanged方法,

- (void) switchValueChanged:(id)sender{

  1. UISwitch* control = (UISwitch*)sender;
  2. if(control == mySwitch){
  3. BOOL on = control.on;
  4. //添加自己要处理的事情代码
  5. }
  6. }

五,代码示例

4.09UISwitch(2)

- (void)onChange:(id)sender

{

UISwitch * tmpSwitch = (UISwitch *)sender;

//强制转换sender的类型,sender代表发送者

if (tmpSwitch.on) {

_label.text = @"开";

//如果它的状态为On的话,_label显示的文本为“开”

}else{

_label.text = @"关";

//如果它的状态为Off的话,_label显示的文本为“关”

}

}

- (void)viewDidLoad

{

[super viewDidLoad];

_label = [[UILabel alloc] initWithFrame:CGRectMake(0, 20, 320, 50)];

//创建一个UILabel对象:_label;

_label.text = @"";

//初始_label显示的文本

_label.textAlignment = UITextAlignmentCenter;

//设置_label文本的对齐方式,默认为左对齐

_label.font = [UIFont fontWithName:@"Arial"size:50];

//设置文本的字体和大小

_label.font = [UIFont systemFontOfSize:20];

//单纯的设置文本的大小

_label.textColor = [UIColor blueColor];

//设置文本的颜色

_label.numberOfLines = 0;

//设置显示的行数,如果为0,则会自动扩充

[self.view addSubview:_label];

//把对象加入到view上

[_label release];

//要记得把对象release

_switch = [[UISwitch alloc] init];

//创建一个UISwitch对象:_switch

_switch.frame = CGRectMake(120, 100, 0, 0);

//设置它的位置,它的大小为79 * 27,不能改动

_switch.on = NO;

//设置它的初始状态为Off,

[self.view addSubview:_switch];

//把对象加入到view

[_switch release];

//要记得把对象release

[_switch addTarget:selfaction:@selector(onChange:) forControlEvents:UIControlEventValueChanged];

//给_switch绑定一个对象,当UIControEventValueChanged时会触发onChange:函数。

}

iOS自定义的UISwitch按钮

 

因为项目需要在UISwitch按钮上写文字,系统自带的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"));

iOS自定义的UISwitch按钮的更多相关文章

  1. iOS 自定义UINavigationController返回按钮

    主要代码如下: //自定义导航栏返回按钮 self.navigationItem.leftBarButtonItem = ({ //导航栏返回背景视图 UIView *view = [[UIView ...

  2. iOS 自定义NavigationBar右侧按钮rightBarButtonItem

    自定义右侧的一个按钮 UIBarButtonItem *myButton = [[UIBarButtonItem alloc] initWithTitle:@"主页" style: ...

  3. iOS 自定义NavigationBar右侧按钮rightBarButtonItem--button

    //两个按钮的父类view UIView *rightButtonView = [[UIView alloc] initWithFrame:CGRectMake(, , , )]; //历史浏览按钮 ...

  4. ios 自定义NavgationBar的按钮

    UIImage *btnimage = [UIImage imageNamed:@"about.png"]; UIButton *btn = [[UIButton alloc] i ...

  5. 【iOS自定义键盘及键盘切换】详解

    [iOS自定义键盘]详解 实现效果展示: 一.实现的协议方法代码 #import <UIKit/UIKit.h> //创建自定义键盘协议 @protocol XFG_KeyBoardDel ...

  6. iOS自定义转场动画实战讲解

    iOS自定义转场动画实战讲解   转场动画这事,说简单也简单,可以通过presentViewController:animated:completion:和dismissViewControllerA ...

  7. iOS 自定义TabBarController

    转自:http://blog.csdn.net/xn4545945/article/details/35994863 一.自定义的思路 iOS中的TabBarController确实已经很强大了,大部 ...

  8. IOS 修改UIAlertController的按钮标题的字体颜色,字号,内容

    IOS 修改UIAlertController的按钮标题的字体颜色,字号,内容 UIAlertController *alertVC = [UIAlertController alertControl ...

  9. iOS 自定义选项卡-CYLTabBarController

    正常的选项卡流程 cocoapods就不说了 创建一个CYLTabBarControllerConfig类 #import <Foundation/Foundation.h> #impor ...

随机推荐

  1. [转载]Web前端和后端之区分,以及面临的挑战

    原文地址:Web前端和后端之区分,以及面临的挑战[转]作者:joyostyle 在我们实际的开发过程中,我们当前这样定位前端.后端开发人员. 1)前端开发人员:精通JS,能熟练应用JQuery,懂CS ...

  2. JS中timestamp日期类型的转换

    在JS中获取timestamp:var timestamp=Math.round(new Date().getTime()/1000); 在JS中将timestamp转换为Date: Date.pro ...

  3. WinForm自定义验证控件

    本文转载:http://blog.csdn.net/ziyouli/article/details/7583824 此篇博文不错:http://blog.csdn.net/sony0732/artic ...

  4. SafeNet推出行业首款白盒password软件保护解决方式

    数据保护领域的全球率先企业SafeNet公司日前宣布,推出行业首款採用白盒安全技术的的软件保护方案.SafeNet 圣天诺 软件授权与保护解决方式如今纳入了新的功能,可在"白盒" ...

  5. Gradle 1.12 翻译——第十三章 编写构建脚本

    有关其它已翻译的章节请关注Github上的项目:https://github.com/msdx/gradledoc/tree/1.12,或訪问:http://gradledoc.qiniudn.com ...

  6. [PWA] 2. Service worker life cycle

    Once serive worker is registered, the first time we go to the app, we cannot see the logs from servc ...

  7. 【Java规划】DOM XML Parser分解、遍历、创XML

    1.前言 DOM XML Parser简介 DOM 它是 W3C 处理 XML 规范 API,这是很多其他的 XML 地基处理相关标准,不仅是 Java,其他的,如 Javascript,PHP.MS ...

  8. Android 模仿QQ空间风格的 UI(转)

    本文内容 环境 演示模仿QQ空间风格的UI 虽然这个 UI 跟现在的QQ空间有点差别,但是也能学到很多东西. 下载 Demo 环境 Windows 7 64 位 Eclipse ADT V22.6.2 ...

  9. new Date()在IE,谷歌,火狐上的一些注意项

    1.new Date()在IE浏览器上IE9以上的可以直接使用new Date("yyyy-MM-dd"),但是在IE8上的时候就要使用new Date("yyyy/MM ...

  10. Linq101-Conversion Operators

    using System; using System.Linq; namespace Linq101 { class Conversion { /// <summary> /// This ...