2016-12-27 56 views
2

我将使用一个将使用大量复选框的项目。我发现了像下面这样的解决方案,但我知道这是不正确的方式。使用复选框的最佳方式 - IOS swift

@IBAction func btn_box(sender: UIButton) { 
    if (btn_box.selected == true) 
    { 
     btn_box.setBackgroundImage(UIImage(named: "box"), forState: UIControlState.Normal) 

      btn_box.selected = false; 
    } 
    else 
    { 
     btn_box.setBackgroundImage(UIImage(named: "checkBox"), forState: UIControlState.Normal) 

     btn_box.selected = true; 
    } 
} 

那么,谁能告诉我有我的项目超过20个复选框的正确方法吗?

我将在表单中使用复选框并进行设置。

谢谢。

+0

您是否在使用Tableview单元格? – Amanpreet

+0

不,我使用的形式和设置目的 – Akram

+0

请按照此链接:http://stackoverflow.com/questions/40782238/how-to-show-checkmark-in-tableview-swift/40782436#40782436 –

回答

14

有很多Checkbox control,或者你通过这个简单的方式做到这一点:

对于情节提要:

  1. 设置按钮的选定图像:

    enter image description here

  2. 设置你的按钮的默认图像:

    enter image description here

对于编程:

btn_box.setBackgroundImage(UIImage(named: "box"), for: .normal) 
btn_box.setBackgroundImage(UIImage(named: "checkBox"), for: .selected) 

而在按键操作:

@IBAction func btn_box(sender: UIButton) { 
    sender.isSelected = !sender.isSelected 
} 
4

而不是检查每个按钮,只是使用通用的方式来处理这个。将所有的按钮,同样IBAction为方法和实施这样的:

@IBAction func btn_box(sender: UIButton) 
{ 
    // Instead of specifying each button we are just using the sender (button that invoked) the method 
    if (sender.selected == true) 
    { 
     sender.setBackgroundImage(UIImage(named: "box"), forState: UIControlState.Normal) 
     sender.selected = false; 
    } 
    else 
    { 
     sender.setBackgroundImage(UIImage(named: "checkBox"), forState: UIControlState.Normal) 
     sender.selected = true; 
    } 
} 
1

您可以使用的方法下面这将最有用: 在你StoryBoardViewDidLoad指定图像的UIButton

checkBoxButton.setBackgroundImage(UIImage(named: "box"), forState: UIControlState.Normal) 
checkBoxButton.setBackgroundImage(UIImage(named: "checkBox"), forState: UIControlState.Selected) 

在这之后你@IBAction方法只是执行下面的代码:

@IBAction func btn_box(sender: UIButton) { 
    sender.selected = !sender.selected 
} 

这将做到这一点。

0

请试试这个。

btn.setImage(UIImage(named: "uncheckImage"), for: UIControlState.normal) 
btn.setImage(UIImage(named: "checkImage"), for: UIControlState.selected) 

@IBAction func btn_box(sender: UIButton) { 

    if btn.isSelected == true { 

      btn.isSelected = false 
    } 
    else { 

      btn.isSelected = true 
    } 
} 
+1

或者可能只是button.isSelected =!button.isSelected – FrostyL

相关问题