如何使用UIButton作为切换开关

rkb*_*rkb 34 iphone

我正在使用自定义类型的UIButton,我想要的是使用它像切换开关一样改变图像.就像点击它之前一样,如果以前没有处于选定模式,它应该进入选定模式,否则反之亦然.此外,它将具有不同的图像,当它被选中时,它将具有不同的图像.

我无法以编程方式执行此操作,是否有任何简单的方法可以执行此操作.

Lee*_*ert 40

我相信这篇文章有一个更好的解决方案: 具有UISwitch功能的iPhone UIButton

UIButton已经内置切换.有一个选定的属性,您可以根据状态设置和更改外观.

  • 忽略下面的所有内容并使用上面的Lee链接. (9认同)

Dim*_*ris 15

在头文件中添加:

IBOutlet UIButton *toggleButton;
BOOL toggleIsOn;

@property (nonatomic, retain) IBOutlet UIButton *toggleButton;
Run Code Online (Sandbox Code Playgroud)

在实施中:

- (IBACtion)toggle:(id)sender
{
  if(toggleIsOn){
    //do anything else you want to do.
  }
  else {
    //do anything you want to do.
  }
  toggleIsOn = !toggleIsOn;
  [self.toggleButton setImage:[UIImage imageNamed:toggleIsOn ? @"on.png" :@"off.png"] forState:UIControlStateNormal];
}
Run Code Online (Sandbox Code Playgroud)

然后将您的按钮与IBActions和IBOutlet链接并初始化toggleIsOn为NO.


int*_*dro 8

在界面中:

@interface TransportViewController : UIViewController {

    UIButton *button;
}
@property(nonatomic, retain) UIButton *button;
Run Code Online (Sandbox Code Playgroud)

在实施中:

- (void)loadView {

[super loadView];

    ...

    [self setButton:[UIButton buttonWithType:UIButtonTypeCustom]];
    [button addTarget:self action:@selector(onClick:) forControlEvents:UIControlEventTouchUpInside];
    [button setImage:[UIImage imageNamed:@"image1"] forState:UIControlStateNormal];
    [button setImage:[UIImage imageNamed:@"image2"] forState:UIControlStateSelected];
}

- (void) onClick:(UIButton *)sender {

    [sender setSelected:!sender.selected];
}
Run Code Online (Sandbox Code Playgroud)


ico*_*ter 7

UIButton默认情况下支持"切换"功能.要使用它,您需要在Interface Builder中为其设置不同的图像甚至文本颜色State Configuration = Selected,并使用选定的属性UIButton来切换其状态.

码:

- (IBAction)yourButtonTouch:(UIButton *)sender {

    sender.selected = !sender.selected;
    if (sender.selected) {
        //...
        // Action to be performed when button is selected or 
        // the first touch
        // ... 

    }
}
Run Code Online (Sandbox Code Playgroud)


Mor*_*ion 0

更改按钮图像并不是一件困难的任务。您可以使用一些 BOOL 值来检测您的开关按钮是否处于“ON”状态。在 onBtnClk 方法中,您只需更改 BOOL 值的状态并设置当前状态的图像。