iOS自定义的UISwitch按钮

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是这样的:

iOS自定义的UISwitch按钮

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

先看下效果图:

iOS自定义的UISwitch按钮

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

看下它的源码:

  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"));
上一篇:【开源】C#信息抽取系统【招募C#队友】


下一篇:macos ssh host配置及免密登陆