服务器之家:专注于服务器技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - IOS - iOS开发中UISwitch按钮的使用方法简介

iOS开发中UISwitch按钮的使用方法简介

2020-12-28 11:03容芳志 IOS

这篇文章主要介绍了iOS开发中UISwitch按钮的使用方法,代码基于传统的Objective-C,需要的朋友可以参考下

一、第一种创建uiswitch控件的方法,在代码中动态创建。
1、打开xcode  4.3.2, 新建项目switch,选择single view application。
2、打开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:需要我们自己实现,就是按下时接收到的事件。
记得把switchbutton加到当前view,调用[self.viewaddsubview:switchbutton];
3、监听uiswitch按下事件
实现代码如下:

复制代码 代码如下:

-(void)switchaction:(id)sender
{
    uiswitch *switchbutton = (uiswitch*)sender;
    bool isbuttonon = [switchbutton ison];
    if (isbuttonon) {
        showswitchvalue.text = @"是";
    }else {
        showswitchvalue.text = @"否";
    }
}


showswitchvalue是我通过拖拽控件方法放到界面上的label,方便显示效果
运行,效果:

 

iOS开发中UISwitch按钮的使用方法简介

二、通过拖拽方法使用uiswitch
1、往xib文件上拖拽一个uiswitch控件。

iOS开发中UISwitch按钮的使用方法简介

2、按alt+command + return键开启assistant editor模式,选中uiswitch控件,按住control键,往viewcontroller.h拖拽

iOS开发中UISwitch按钮的使用方法简介

3、选action方式

iOS开发中UISwitch按钮的使用方法简介

4、.m文件中实现switchaction 。刚才动态创建的时候也用到这个方法名称,可以先注释掉刚才的。

复制代码 代码如下:

- (ibaction)switchaction:(id)sender {
    uiswitch *switchbutton = (uiswitch*)sender;
    bool isbuttonon = [switchbutton ison];
    if (isbuttonon) {
        showswitchvalue.text = @"是";
    }else {
        showswitchvalue.text = @"否";
    }
}


这里我们来看一下.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"));
 
}

延伸 · 阅读

精彩推荐
  • IOSiOS布局渲染之UIView方法的调用时机详解

    iOS布局渲染之UIView方法的调用时机详解

    在你刚开始开发 iOS 应用时,最难避免或者是调试的就是和布局相关的问题,下面这篇文章主要给大家介绍了关于iOS布局渲染之UIView方法调用时机的相关资料...

    windtersharp7642021-05-04
  • IOSiOS 雷达效果实例详解

    iOS 雷达效果实例详解

    这篇文章主要介绍了iOS 雷达效果实例详解的相关资料,需要的朋友可以参考下...

    SimpleWorld11022021-01-28
  • IOSiOS通过逆向理解Block的内存模型

    iOS通过逆向理解Block的内存模型

    自从对 iOS 的逆向初窥门径后,我也经常通过它来分析一些比较大的应用,参考一下这些应用中某些功能的实现。这个探索的过程乐趣多多,不仅能满足自...

    Swiftyper12832021-03-03
  • IOSIOS开发之字典转字符串的实例详解

    IOS开发之字典转字符串的实例详解

    这篇文章主要介绍了IOS开发之字典转字符串的实例详解的相关资料,希望通过本文能帮助到大家,让大家掌握这样的方法,需要的朋友可以参考下...

    苦练内功5832021-04-01
  • IOSIOS 屏幕适配方案实现缩放window的示例代码

    IOS 屏幕适配方案实现缩放window的示例代码

    这篇文章主要介绍了IOS 屏幕适配方案实现缩放window的示例代码,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要...

    xiari5772021-06-01
  • IOSiOS中tableview 两级cell的展开与收回的示例代码

    iOS中tableview 两级cell的展开与收回的示例代码

    本篇文章主要介绍了iOS中tableview 两级cell的展开与收回的示例代码,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧...

    J_Kang3862021-04-22
  • IOS关于iOS自适应cell行高的那些事儿

    关于iOS自适应cell行高的那些事儿

    这篇文章主要给大家介绍了关于iOS自适应cell行高的那些事儿,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的...

    daisy6092021-05-17
  • IOS解析iOS开发中的FirstResponder第一响应对象

    解析iOS开发中的FirstResponder第一响应对象

    这篇文章主要介绍了解析iOS开发中的FirstResponder第一响应对象,包括View的FirstResponder的释放问题,需要的朋友可以参考下...

    一片枫叶4662020-12-25