ios之自定义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"));
- }
代码下载地址:https://github.com/schelling/HMCustomSwitch
ios之自定义UISwitch的更多相关文章
- 1.2UISwitch 1.3 自定义UIswitch 1.4pickerView
1.2 UISwitch创建和使用开关 问题你想给你的用户打开一个选项或关闭的能力.解使用UISwitch类. 讨论该UISwitch类提供像在图1-7为自动大写,自动校正,等等所示的开/ ...
- iOS 如何自定义UISearchBar 中textField的高度
iOS 如何自定义UISearchBar 中textField的高度 只需设置下边的方法就可以 [_searchBar setSearchFieldBackgroundImage:[UIImage i ...
- iOS 隐藏自定义tabbar
iOS 隐藏自定义tabbar -(void)viewWillAppear:(BOOL)animated { NSArray *array=self.tabBarController.view.su ...
- ios 实现自定义状态栏StatusBar 和 导航栏navigationBar 的状态和颜色
很多app中可以看到不同与导航栏的状态栏的颜色,他妈的真绕嘴. 一.更改状态栏颜色 (StatusBar) 就是比如导航栏是红色的状态栏是绿色的. 要实现这样的效果其实很简单,就是添加一个背景view ...
- ios UIWebView自定义Alert风格的弹框
之前开发过一个App,因为公司之前写好了网页版的内容和安卓版本的App,我进去后老板要求我ios直接用网页的内容,而不需要自己再搭建框架.我一听,偷笑了,这不就是一个UIWebView吗?简单! 但是 ...
- 【IOS】自定义可点击的多文本跑马灯YFRollingLabel
需求 项目中需要用到跑马灯来仅展示一条消息,长度合适则不滚动,过长则循环滚动. 虽然不是我写的,但看了看代码,是在一个UIView里面放入两个UILabel, 在前一个快结束的时候,另一个显示.然而点 ...
- iOS - 使用自定义字体-苹方字体
苹方提供了六个字重,font-family 定义如下:苹方-简 常规体font-family: PingFangSC-Regular, sans-serif;苹方-简 极细体font-family: ...
- [IOS]swift自定义uicollectionviewcell
刚刚接触swift以及ios,不是很理解有的逻辑,导致某些问题.这里分享一下swift自定义uicollectionviewcell 首先我的viewcontroller不是直接继承uicollect ...
- ios中自定义tableView,CollectionView的cell什么时候用nib加载,什么时候用标识重用
做了一段时间的iOS,在菜鸟的路上还有很长的路要走,把遇到的问题记下来,好记性不如烂笔头. 在项目开发中大家经常会用到tableView和collectionView两个控件,然而在cell的自定义上 ...
随机推荐
- java数据结构----图
1.图:.在计算机程序设计中,图是最常用的数据结构之一.对于存储一般的数据问题,一般用不到图.但对于某些(特别是一些有趣的问题),图是必不可少的.图是一种与树有些相像的数据结构,从数学意义上来讲,树是 ...
- ICM Technex 2017 and Codeforces Round #400 (Div. 1 + Div. 2, combined) C
Molly Hooper has n different kinds of chemicals arranged in a line. Each of the chemicals has an aff ...
- Storm编程入门API系列之Storm的Topology多个tasks数目控制实现
前期博客 Storm编程入门API系列之Storm的Topology默认Workers.默认executors和默认tasks数目 Storm编程入门API系列之Storm的Topology多个Wor ...
- 【algorithm】二叉树的遍历
二叉树的遍历 二叉树用例 代码解析: public class BinaryTree { static class TreeNode { Integer val; TreeNode left; Tre ...
- 在Window上用cmd创建.htaccess文件
Windows 图形下不能直接建立空名字的文件,所以没法直接创建.htaccess文件,不过可以通过命令行创建: cd /path/to/your/dir/ type nul>.htaccess ...
- table表格字母无法换行
在项目中,用到的table比较多,本来布局挺好的,后来在td内写入英文字母,整个布局就乱了,会撑的很宽,不换行,后来才知道:一般字母的话会被浏览器默认是一个字符串或者说一个单词,所以不会自动换行. 于 ...
- Eclipse-运行符-数据类型转换-环境变量配置
1.能够使用Eclipse快捷键 ctrl + / 单行注释:再按一次则取消: ctrl + shift + / 多行注释: ctrl + shift + \ 取消多行注释: ctrl + ...
- git处理时的问题
1. 在node.js开发的时候常常会遇到从别人的远程仓库中clone时出现文件名过长的错误, 或则是在本地npm下载之后的文件进行上传到自己的远程仓库的时候会出现 File too long的情况, ...
- jmeter中通过beanshell访问eclipse中导出jar中的java类的方法
主要步骤 1.在eclipse中导出要引用的java代码为jar文件 2.将生成的jar文件放到jmeter的lib的ext目录下 3.在jmeter的jsr223处理器中导入要引用的java类型文件 ...
- POJ 2486 Apple Tree (树形DP,树形背包)
题意:给定一棵树图,一个人从点s出发,只能走K步,每个点都有一定数量的苹果,要求收集尽量多的苹果,输出最多苹果数. 思路: 既然是树,而且有限制k步,那么树形DP正好. 考虑1个点的情况:(1)可能在 ...