iOS自定义的UISwitch按钮
UISwitch开关控件
开关代替了点选框。开关是到目前为止用起来最简单的控件,不过仍然可以作一定程度的定制化。
一、创建
- UISwitch* mySwitch = [[ UISwitchalloc]initWithFrame:CGRectMake(200.0,10.0,0.0,0.0)];
是不是很奇怪,大小竟然是0.0×0.0,没错,系统会自动帮你决定最佳的尺寸,你自己写的尺寸会被忽略掉,你只要定义好相对父视图的位置就好了。默认尺寸为79 * 27。
二、显示控件
- [ parrentView addSubview:mySwitch];//添加到父视图
或
- self.navigationItem.titleView = mySwitch;//添加到导航栏
三、开关状态
开关状态可以通过它的on属性读取,这个属性是一个BOOL值,表示开关是否被打开:
- BOOL switchStatus = mySwitch.on;
你可以在你的代码中用setOn方法来打开或关闭开关:
- [ mySwitch setOn:YES animated:YES];
四、通知想要在开关状态切换时收到通知,可以用UIControl类的addTarget方法为UIControlEventValueChanged事件添加一个动作。
- [ mySwitch addTarget: self action:@selector(switchValueChanged:) forControlEvents:UIControlEventValueChanged];
这样,只要开关一被切换目标类(上例中目标类就是当前控制器self)就会调用switchValueChanged方法,
- (void) switchValueChanged:(id)sender{
- UISwitch* control = (UISwitch*)sender;
- if(control == mySwitch){
- BOOL on = control.on;
- //添加自己要处理的事情代码
- }
- }
五,代码示例
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按钮,具体出处找不见了。记录一下,怕以后找不见了。
先看下效果图:
按钮的样式很多,可以文字,可以写多行,文字大小和颜色都可以设置。
看下它的源码:
- #import <Foundation/Foundation.h>
- @interface HMCustomSwitch : UISlider {
- BOOL on;
- UIColor *tintColor;
- UIView *clippingView;
- UILabel *rightLabel;
- UILabel *leftLabel;
- // private member
- BOOL m_touchedSelf;
- }
- @property(nonatomic,getter=isOn) BOOL on;
- @property (nonatomic,retain) UIColor *tintColor;
- @property (nonatomic,retain) UIView *clippingView;
- @property (nonatomic,retain) UILabel *rightLabel;
- @property (nonatomic,retain) UILabel *leftLabel;
- + (HMCustomSwitch *) switchWithLeftText: (NSString *) tag1 andRight: (NSString *) tag2;
- - (void)setOn:(BOOL)on animated:(BOOL)animated;
.m文件
- #import "HMCustomSwitch.h"
- @implementation HMCustomSwitch
- @synthesize on;
- @synthesize tintColor, clippingView, leftLabel, rightLabel;
- +(HMCustomSwitch *)switchWithLeftText:(NSString *)leftText andRight:(NSString *)rightText
- {
- HMCustomSwitch *switchView = [[HMCustomSwitch alloc] initWithFrame:CGRectZero];
- switchView.leftLabel.text = leftText;
- switchView.rightLabel.text = rightText;
- return [switchView autorelease];
- }
- -(id)initWithFrame:(CGRect)rect
- {
- if ((self=[super initWithFrame:CGRectMake(rect.origin.x,rect.origin.y,95,27)]))
- {
- // self.clipsToBounds = YES;
- [self awakeFromNib]; // do all setup in awakeFromNib so that control can be created manually or in a nib file
- }
- return self;
- }
- -(void)awakeFromNib
- {
- [super awakeFromNib];
- self.backgroundColor = [UIColor clearColor];
- [self setThumbImage:[UIImage imageNamed:@"switchThumb.png"] forState:UIControlStateNormal];
- [self setMinimumTrackImage:[UIImage imageNamed:@"switchBlueBg.png"] forState:UIControlStateNormal];
- [self setMaximumTrackImage:[UIImage imageNamed:@"switchOffPlain.png"] forState:UIControlStateNormal];
- self.minimumValue = 0;
- self.maximumValue = 1;
- self.continuous = NO;
- self.on = NO;
- self.value = 0.0;
- self.clippingView = [[UIView alloc] initWithFrame:CGRectMake(4,2,87,23)];
- self.clippingView.clipsToBounds = YES;
- self.clippingView.userInteractionEnabled = NO;
- self.clippingView.backgroundColor = [UIColor clearColor];
- [self addSubview:self.clippingView];
- [self.clippingView release];
- NSString *leftLabelText = NSLocalizedString(@"ON","Custom UISwitch ON label. If localized to empty string then I/O will be used");
- if ([leftLabelText length] == 0)
- {
- leftLabelText = @"l"; // use helvetica lowercase L to be a 1.
- }
- self.leftLabel = [[UILabel alloc] init];
- self.leftLabel.frame = CGRectMake(0, 0, 48, 23);
- self.leftLabel.text = leftLabelText;
- self.leftLabel.textAlignment = NSTextAlignmentCenter;
- self.leftLabel.font = [UIFont boldSystemFontOfSize:17];
- self.leftLabel.textColor = [UIColor whiteColor];
- self.leftLabel.backgroundColor = [UIColor clearColor];
- // self.leftLabel.shadowColor = [UIColor redColor];
- // self.leftLabel.shadowOffset = CGSizeMake(0,0);
- [self.clippingView addSubview:self.leftLabel];
- [self.leftLabel release];
- NSString *rightLabelText = NSLocalizedString(@"OFF","Custom UISwitch OFF label. If localized to empty string then I/O will be used");
- if ([rightLabelText length] == 0)
- {
- rightLabelText = @"O"; // use helvetica uppercase o to be a 0.
- }
- self.rightLabel = [[UILabel alloc] init];
- self.rightLabel.frame = CGRectMake(95, 0, 48, 23);
- self.rightLabel.text = rightLabelText;
- self.rightLabel.textAlignment = NSTextAlignmentCenter;
- self.rightLabel.font = [UIFont boldSystemFontOfSize:17];
- self.rightLabel.textColor = [UIColor grayColor];
- self.rightLabel.backgroundColor = [UIColor clearColor];
- // self.rightLabel.shadowColor = [UIColor redColor];
- // self.rightLabel.shadowOffset = CGSizeMake(0,0);
- [self.clippingView addSubview:self.rightLabel];
- [self.rightLabel release];
- }
- -(void)layoutSubviews
- {
- [super layoutSubviews];
- // NSLog(@"leftLabel=%@",NSStringFromCGRect(self.leftLabel.frame));
- // move the labels to the front
- [self.clippingView removeFromSuperview];
- [self addSubview:self.clippingView];
- CGFloat thumbWidth = self.currentThumbImage.size.width;
- CGFloat switchWidth = self.bounds.size.width;
- CGFloat labelWidth = switchWidth - thumbWidth;
- CGFloat inset = self.clippingView.frame.origin.x;
- // NSInteger xPos = self.value * (self.bounds.size.width - thumbWidth) - (self.leftLabel.frame.size.width - thumbWidth/2);
- NSInteger xPos = self.value * labelWidth - labelWidth - inset;
- self.leftLabel.frame = CGRectMake(xPos, 0, labelWidth, 23);
- // xPos = self.value * (self.bounds.size.width - thumbWidth) + (self.rightLabel.frame.size.width - thumbWidth/2);
- xPos = switchWidth + (self.value * labelWidth - labelWidth) - inset;
- self.rightLabel.frame = CGRectMake(xPos, 0, labelWidth, 23);
- // NSLog(@"value=%f xPos=%i",self.value,xPos);
- // NSLog(@"thumbWidth=%f self.bounds.size.width=%f",thumbWidth,self.bounds.size.width);
- }
- - (UIImage *)image:(UIImage*)image tintedWithColor:(UIColor *)tint
- {
- if (tint != nil)
- {
- UIGraphicsBeginImageContext(image.size);
- //draw mask so the alpha is respected
- CGContextRef currentContext = UIGraphicsGetCurrentContext();
- CGImageRef maskImage = [image CGImage];
- CGContextClipToMask(currentContext, CGRectMake(0, 0, image.size.width, image.size.height), maskImage);
- CGContextDrawImage(currentContext, CGRectMake(0,0, image.size.width, image.size.height), image.CGImage);
- [image drawAtPoint:CGPointMake(0,0)];
- [tint setFill];
- UIRectFillUsingBlendMode(CGRectMake(0,0,image.size.width,image.size.height),kCGBlendModeColor);
- UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
- UIGraphicsEndImageContext();
- return newImage;
- }
- else
- {
- return image;
- }
- }
- -(void)setTintColor:(UIColor*)color
- {
- if (color != tintColor)
- {
- [tintColor release];
- tintColor = [color retain];
- [self setMinimumTrackImage:[self image:[UIImage imageNamed:@"switchBlueBg.png"] tintedWithColor:tintColor] forState:UIControlStateNormal];
- }
- }
- - (void)setOn:(BOOL)turnOn animated:(BOOL)animated;
- {
- on = turnOn;
- if (animated)
- {
- [UIView beginAnimations:nil context:nil];
- [UIView setAnimationDuration:0.2];
- }
- if (on)
- {
- self.value = 1.0;
- }
- else
- {
- self.value = 0.0;
- }
- if (animated)
- {
- [UIView commitAnimations];
- }
- }
- - (void)setOn:(BOOL)turnOn
- {
- [self setOn:turnOn animated:NO];
- }
- - (void)endTrackingWithTouch:(UITouch *)touch withEvent:(UIEvent *)event
- {
- NSLog(@"preendTrackingWithtouch");
- [super endTrackingWithTouch:touch withEvent:event];
- NSLog(@"postendTrackingWithtouch");
- m_touchedSelf = YES;
- [self setOn:on animated:YES];
- }
- - (void)touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event
- {
- [super touchesBegan:touches withEvent:event];
- NSLog(@"touchesBegan");
- m_touchedSelf = NO;
- on = !on;
- }
- - (void)touchesEnded:(NSSet*)touches withEvent:(UIEvent*)event
- {
- [super touchesEnded:touches withEvent:event];
- NSLog(@"touchesEnded");
- if (!m_touchedSelf)
- {
- [self setOn:on animated:YES];
- [self sendActionsForControlEvents:UIControlEventValueChanged];
- }
- }
- -(void)dealloc
- {
- [tintColor release];
- [clippingView release];
- [rightLabel release];
- [leftLabel release];
- [super dealloc];
- }
- @end
看代码可以知道,其实它是通过继承UISlider控件实现的,UISlider的左右分别是个UILabel,当YES的时候,滑块滑到了最右边,NO的时候滑到了最左边。
如何在代码中使用它呢?很简单:
- - (void)loadView
- {
- UIView *contentView = [[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]];
- self.view = contentView;
- contentView.backgroundColor = [UIColor whiteColor];
- // Standard ON/OFF
- HMCustomSwitch *switchView = [[HMCustomSwitch alloc] initWithFrame:CGRectZero];
- switchView.center = CGPointMake(160.0f, 20.0f);
- switchView.on = YES;
- [contentView addSubview:switchView];
- [switchView release];
- // Custom YES/NO
- switchView = [HMCustomSwitch switchWithLeftText:@"YES" andRight:@"NO"];
- switchView.center = CGPointMake(160.0f, 60.0f);
- switchView.on = YES;
- [contentView addSubview:switchView];
- // Custom font and color
- switchView = [HMCustomSwitch switchWithLeftText:@"Hello " andRight:@"ABC "];
- switchView.center = CGPointMake(160.0f, 100.0f);
- switchView.on = YES;
- [switchView.leftLabel setFont:[UIFont boldSystemFontOfSize:13.0f]];
- [switchView.rightLabel setFont:[UIFont italicSystemFontOfSize:15.0f]];
- [switchView.rightLabel setTextColor:[UIColor blueColor]];
- [contentView addSubview:switchView];
- // Multiple lines
- switchView = [HMCustomSwitch switchWithLeftText:@"Hello\nWorld" andRight:@"Bye\nWorld"];
- switchView.center = CGPointMake(160.0f, 140.0f);
- switchView.on = YES;
- switchView.tintColor = [UIColor orangeColor];
- switchView.leftLabel.font = [UIFont boldSystemFontOfSize:9.0f];
- switchView.rightLabel.font = [UIFont boldSystemFontOfSize:9.0f];
- switchView.leftLabel.numberOfLines = 2;
- switchView.rightLabel.numberOfLines = 2;
- switchView.leftLabel.lineBreakMode = NSLineBreakByWordWrapping;
- switchView.rightLabel.lineBreakMode = NSLineBreakByWordWrapping;
- [contentView addSubview:switchView];
- switchView = [[HMCustomSwitch alloc] init];
- switchView.center = CGPointMake(160.0f, 180.0f);
- switchView.on = YES;
- switchView.tintColor = [UIColor purpleColor];
- [contentView addSubview:switchView];
- [switchView release];
- switchView = [HMCustomSwitch switchWithLeftText:@"l" andRight:@"O"];
- switchView.center = CGPointMake(160.0f, 220.0f);
- // customSwitch.tintColor = [UIColor colorWithRed:125.f/255.f green:157.f/255.f blue:93.f/255.f alpha:1.0];
- // customSwitch.tintColor = [UIColor colorWithRed:125.f/255.f green:157.f/255.f blue:93.f/255.f alpha:1.0];
- [contentView addSubview:switchView];
- // Standard ON/OFF
- switchView = [[HMCustomSwitch alloc] init];
- switchView.center = CGPointMake(160.0f, 260.0f);
- switchView.tintColor = [UIColor colorWithRed:125.f/255.f green:157.f/255.f blue:93.f/255.f alpha:1.0];
- [switchView addTarget:self action:@selector(switchFlipped:) forControlEvents:UIControlEventValueChanged];
- [contentView addSubview:switchView];
- [switchView release];
- UIToolbar *toolbar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 420, 320, 40)];
- toolbar.tintColor = [UIColor colorWithRed:125.f/255.f green:157.f/255.f blue:93.f/255.f alpha:1.0];
- [contentView addSubview:toolbar];
- [contentView release];
- }
- -(void)switchFlipped:(HMCustomSwitch*)switchView
- {
- NSLog(@"switchFlipped=%f on:%@",switchView.value, (switchView.on?@"Y":@"N"));
iOS自定义的UISwitch按钮的更多相关文章
- iOS 自定义UINavigationController返回按钮
主要代码如下: //自定义导航栏返回按钮 self.navigationItem.leftBarButtonItem = ({ //导航栏返回背景视图 UIView *view = [[UIView ...
- iOS 自定义NavigationBar右侧按钮rightBarButtonItem
自定义右侧的一个按钮 UIBarButtonItem *myButton = [[UIBarButtonItem alloc] initWithTitle:@"主页" style: ...
- iOS 自定义NavigationBar右侧按钮rightBarButtonItem--button
//两个按钮的父类view UIView *rightButtonView = [[UIView alloc] initWithFrame:CGRectMake(, , , )]; //历史浏览按钮 ...
- ios 自定义NavgationBar的按钮
UIImage *btnimage = [UIImage imageNamed:@"about.png"]; UIButton *btn = [[UIButton alloc] i ...
- 【iOS自定义键盘及键盘切换】详解
[iOS自定义键盘]详解 实现效果展示: 一.实现的协议方法代码 #import <UIKit/UIKit.h> //创建自定义键盘协议 @protocol XFG_KeyBoardDel ...
- iOS自定义转场动画实战讲解
iOS自定义转场动画实战讲解 转场动画这事,说简单也简单,可以通过presentViewController:animated:completion:和dismissViewControllerA ...
- iOS 自定义TabBarController
转自:http://blog.csdn.net/xn4545945/article/details/35994863 一.自定义的思路 iOS中的TabBarController确实已经很强大了,大部 ...
- IOS 修改UIAlertController的按钮标题的字体颜色,字号,内容
IOS 修改UIAlertController的按钮标题的字体颜色,字号,内容 UIAlertController *alertVC = [UIAlertController alertControl ...
- iOS 自定义选项卡-CYLTabBarController
正常的选项卡流程 cocoapods就不说了 创建一个CYLTabBarControllerConfig类 #import <Foundation/Foundation.h> #impor ...
随机推荐
- nginx 配置301转发
学习nginx 推荐 http://www.nginx.cn/nginx-how-to 1. 设置域名解析 daijun.me 指向 234.33.22.21 2.主机234.33.22.21 ngi ...
- typedef struct
突然忘了这玩意儿了..今天就来搞一发 typedef是类型定义的意思.typedef struct 是为了使用这个结构体方便.具体区别在于:若struct node {}这样来定义结构体的话.在申请n ...
- C++中一个函数隐藏的有趣例子
函数隐藏是一个函数的定义或声明导致其他一些函数不可见. 函数A隐藏函数B的条件: 1. 两个函数具有相同的函数名称 2. 具有不同的作用域.所谓定义域函数定义或声明的位置,如全局作 ...
- dubbo(soa分布式)与cobar(mysql分布式)
http://www.jianshu.com/p/0dde591f21d0 (Dubbo编译不是个顺利的事) Cobar是提供关系型数据库(MySQL)分布式服务的中间件,它可以让传统的数据库得到良好 ...
- 在一个UIView中如何使用多个UIPickerView
可以现在storyboard的UIView中拖入多个UIPickerView 然后同样是继承相关的UIPickerView协议 <UIPickerViewDataSource,UIPickerV ...
- 解决下载android sdk慢的问题
修改host文件 203.208.46.146 dl.google.com 203.208.46.146 dl-ssl.google.com 强制不使用https访问 在sdk manager里选择t ...
- composer 说明<转>
转自 http://blog.csdn.net/zzulp/article/details/18981029 Composer是一个基于项目的依赖管理器,负责将PHP项目所依赖的包或库安装到项目所在 ...
- Struts2里如何取得request,session,application
第一种:取得MAP类型的request,session,application在java文件里写 package com.xjtu.st; import java.util.Map; import c ...
- 很棒的jQuery代码片段分享
jQuery实现的内链接平滑滚动 不需要使用太复杂的插件,只要使用下载这段代码即可实现基于内部链接的平滑滚动 $('a[href^="#"]').bind('click.smoot ...
- HTML5 Canvas Text文本居中实例
1.代码: <canvas width="700" height="300" id="canvasOne" class="c ...