iOS開(kāi)發(fā)中UISwitch按鈕的使用方法簡(jiǎn)介
一、第一種創(chuàng)建UISwitch控件的方法,在代碼中動(dòng)態(tài)創(chuàng)建。
1、打開(kāi)Xcode 4.3.2, 新建項(xiàng)目Switch,選擇Single View Application。
2、打開(kāi)ViewController.m文件在viewDidLoad方法里添加代碼:
- (void)viewDidLoad
{
[super viewDidLoad];
UISwitch *switchButton = [[UISwitch alloc] initWithFrame:CGRectMake(50, 100, 20, 10)];
[switchButton setOn:YES];
[switchButton addTarget:self action:@selector(switchAction:) forControlEvents:UIControlEventValueChanged];
[self.view addSubview:switchButton];
// Do any additional setup after loading the view, typically from a nib.
}
代碼中selector中的switchAction:需要我們自己實(shí)現(xiàn),就是按下時(shí)接收到的事件。
記得把switchButton加到當(dāng)前view,調(diào)用[self.viewaddSubview:switchButton];
3、監(jiān)聽(tīng)UISwitch按下事件
實(shí)現(xiàn)代碼如下:
-(void)switchAction:(id)sender
{
UISwitch *switchButton = (UISwitch*)sender;
BOOL isButtonOn = [switchButton isOn];
if (isButtonOn) {
showSwitchValue.text = @"是";
}else {
showSwitchValue.text = @"否";
}
}
showSwitchValue是我通過(guò)拖拽控件方法放到界面上的Label,方便顯示效果
運(yùn)行,效果:
二、通過(guò)拖拽方法使用UISwitch
1、往xib文件上拖拽一個(gè)UISwitch控件。
2、按alt+command + return鍵開(kāi)啟Assistant Editor模式,選中UISwitch控件,按住Control鍵,往ViewController.h拖拽
3、選Action方式
4、.m文件中實(shí)現(xiàn)switchAction 。剛才動(dòng)態(tài)創(chuàng)建的時(shí)候也用到這個(gè)方法名稱,可以先注釋掉剛才的。
- (IBAction)switchAction:(id)sender {
UISwitch *switchButton = (UISwitch*)sender;
BOOL isButtonOn = [switchButton isOn];
if (isButtonOn) {
showSwitchValue.text = @"是";
}else {
showSwitchValue.text = @"否";
}
}
這里我們來(lái)看一下.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
看代碼可以知道,其實(shí)它是通過(guò)繼承UISlider控件實(shí)現(xiàn)的,UISlider的左右分別是個(gè)UILabel,當(dāng)YES的時(shí)候,滑塊滑到了最右邊,NO的時(shí)候滑到了最左邊。
所以在代碼中使用它呢?這里再舉一個(gè)例子:
- (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中Button按鈕的狀態(tài)和點(diǎn)擊事件
- 關(guān)于iOS導(dǎo)航欄返回按鈕問(wèn)題的解決方法
- IOS UITableViewCell詳解及按鈕點(diǎn)擊事件處理實(shí)例
- 詳解iOS應(yīng)用中自定義UIBarButtonItem導(dǎo)航按鈕的創(chuàng)建方法
- 詳解iOS-按鈕單選與多選邏輯處理
- iOS應(yīng)用開(kāi)發(fā)中導(dǎo)航欄按鈕UIBarButtonItem的添加教程
- iOS App中UITableView左滑出現(xiàn)刪除按鈕及其cell的重用
- 學(xué)習(xí)iOS開(kāi)關(guān)按鈕UISwitch控件
- iOS 防止按鈕多次點(diǎn)擊造成多次響應(yīng)的方法
- iOS實(shí)現(xiàn)全局懸浮按鈕
相關(guān)文章
iOS實(shí)現(xiàn)知乎和途家導(dǎo)航欄漸變的文字動(dòng)畫(huà)效果
這篇文章給大家分享了利用iOS實(shí)現(xiàn)知乎和途家導(dǎo)航欄漸變的文字動(dòng)畫(huà)效果,有需要的朋友們可以參考借鑒。下面來(lái)一起看看。2016-09-09iOS應(yīng)用開(kāi)發(fā)中矢量圖的使用及修改矢量圖顏色的方法
這篇文章主要介紹了iOS應(yīng)用開(kāi)發(fā)中矢量圖的使用及修改矢量圖顏色的方法,文中的方法是在Adobe Illustrator中繪制矢量圖然后導(dǎo)入Xcode中使用,需要的朋友可以參考下2016-03-03iOS應(yīng)用開(kāi)發(fā)中StoryBoard搭建UI界面的基本使用講解
這篇文章主要介紹了iOS應(yīng)用開(kāi)發(fā)中StoryBoard搭建UI界面的基本使用,代碼基于傳統(tǒng)的Objective-C,需要的朋友可以參考下2016-02-02iOS如何用100行代碼實(shí)現(xiàn)簡(jiǎn)單的抽屜效果
最近在網(wǎng)上看到一些抽屜效果,看起來(lái)很酷!很眩!但是,下不下來(lái)看代碼, 所以決定還是自己寫(xiě)吧!!這篇文章通過(guò)近100行的代碼就實(shí)現(xiàn)了簡(jiǎn)單的抽屜效果,有需要的朋友們可以參考借鑒,下面來(lái)一起看看吧。2016-10-10iOS開(kāi)發(fā)中不合法的網(wǎng)絡(luò)請(qǐng)求地址如何解決
這篇文章主要介紹了iOS開(kāi)發(fā)中不合法的網(wǎng)絡(luò)請(qǐng)求地址的解決方案,非常不錯(cuò),具有參考借鑒價(jià)值,需要的朋友可以參考下2016-09-09IOS開(kāi)發(fā)基礎(chǔ)之二維數(shù)組詳解
這篇文章主要介紹了IOS開(kāi)發(fā)基礎(chǔ)之二維數(shù)組詳解的相關(guān)資料,需要的朋友可以參考下2017-04-04iOS中PNChart與UITableView的聯(lián)動(dòng)示例詳解
PNChart是個(gè)界面很漂亮的圖表第三方庫(kù),UITableView則不用過(guò)多介紹了,各位iOS開(kāi)發(fā)者們都知道,下面這篇文章主要給大家介紹了關(guān)于iOS中PNChart與UITableView的聯(lián)動(dòng)的相關(guān)資料,需要的朋友可以參考下2018-07-07