如何在iOS中使用Swift更改UIButton的状态?
我有六个button的Objective-C工作代码,但我似乎没有find如何使用Swift更改button的状态。 那么如何让下面的代码在Swift中工作呢?
[self.button2 setBackgroundImage:[UIImage imageNamed:@"button2_selected.png"] forState: UIControlStateSelected]; button1.selected = NO; button2.selected = !button2.selected; button3.selected = NO; button4.selected = NO; button5.selected = NO; button6.selected = NO;
检查这个:
var var_button_ = UIButton() var_button_.setBackgroundImage(UIImage(named: "button2_selected.png"), forState: UIControlState.Normal) var_button_.selected = false var_button_.selected = !var_button_.selected //var_button_.selected = true
感谢JNYJ
//你需要在swift中使用true和false作为bool值
buttonOutletName.selected = true buttonOutletName.selected = false
/ /创buildIBAction和检查buttonselect或没有迅速的语言。 您可以更改button状态。
@IBAction func favoriteButtonAction(sender: UIButton) { // Save Data sender.selected = !sender.selected; if (sender.selected) { NSLog(" Not Selected"); sender.selected = false self.setImage(UIImage(named: "checked_checkbox"), forState: .Normal) } else { NSLog(" Selected"); sender.selected = false self.setImage(UIImage(named: "unchecked_checkbox"), forState: .Normal) } }
为您的button创build一个sockets和一个动作
为状态configurationselect和默认分别给“button_selected”和“button_not_selected”图像。
然后在动作中写下面的代码,
if button.isSelected { button.isSelected = false } else { button.isSelected = true }
我认为这是最简单的方法
//方法1 //创buildIBAction并选中或不选中button…不需要在if / else语句中将//sender.selected设置为true或false。
@IBAction func rememberMe(sender: UIButton) { sender.selected = !sender.selected if sender.selected { self.setImage(UIImage(named: "RememberMe_Checkmark"), forState: .Normal) } else { self.setImage(UIImage(named: "No_Checkmark"), forState: .Normal) } }
//方法2使用来自Storyboard的自定义types
在这里input图片描述点击图片链接查看样本
从故事板执行以下操作
1)将buttontypes更改为“自定义”
2)将状态configuration更改为“选定”
3)使用复选标记资源将图像设置为checkbox图标
4)将背景设置为checkbox图标,而不勾选资产
//从button创build和IBAction并input这一行代码
@IBAction func rememberMe(sender: UIButton) { sender.selected = !sender.selected }