使用复选框的最佳方式 - IOS swift

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41344895/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 10:59:01  来源:igfitidea点击:

The best way to use checkbox - IOS swift

iosswiftcheckbox

提问by A.khalifa

I am going to work on a project that will use a lot of checkboxes. I found a solution like below, but I know this not right way.

我将从事一个将使用大量复选框的项目。我找到了如下解决方案,但我知道这不是正确的方法。

 @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;
    }
}

So, can anyone show me the right way of having more than 20 checkboxes in my project?

那么,谁能告诉我在我的项目中拥有 20 多个复选框的正确方法吗?

I will use checkboxes in forms and for settings purpose.

我将在表单和设置中使用复选框。

Thanks.

谢谢。

回答by Bhavin Ramani

There are lots of Checkbox controlor you do it by this simple way:

有很多Checkbox 控件,或者您可以通过这种简单的方式来实现:

For Storyboard:

对于故事板:

  1. Set your button's selected image:

    enter image description here

  2. Set your button's default image:

    enter image description here

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

    在此处输入图片说明

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

    在此处输入图片说明

For Programmatically:

以编程方式:

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

And in button action:

在按钮操作中:

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

回答by Midhun MP

Instead of checking each and every button, just use a generic way to handle this. Set all your button to the same IBAction method and implement that like:

无需检查每个按钮,只需使用通用方法来处理此问题。将所有按钮设置为相同的 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;
    }
}

回答by Arasuvel

You can use the approach below which will most helpful: In your StoryBoardor ViewDidLoadassign the image for UIButton:

您可以使用以下最有帮助的方法:在您的StoryBoardViewDidLoad分配图像中UIButton

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

After this in your @IBActionMethod just implement the following code:

在您的@IBAction方法之后,只需实现以下代码:

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

This will do the trick.

这将解决问题。

回答by Keyur Hirani

Please try this.

请试试这个。

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
     }
}

回答by Jaimin Patel

It gives me a great pleasure to inform you all that solve above issue

很高兴通知您所有解决上述问题的人

Resolving Issue Is

解决问题是

  1. CheckBox Functionality
  2. RadioButton Functionality
  3. ReuseCell(tableView.dequeueReusableCell)//Also solve selected cell position issue.
  1. 复选框功能
  2. 单选按钮功能
  3. ReuseCell(tableView.dequeueReusableCell)//同时解决选中单元格位置问题。

Tested Code

测试代码

  • Swift 5
  • iOS 12.2
  • 斯威夫特 5
  • iOS 12.2

Here is my code

这是我的代码

import UIKit

class countrySelection:UITableViewCell{
     @IBOutlet weak var imgFlag: UIImageView!
     @IBOutlet weak var lblCountryName: UILabel!
     @IBOutlet weak var btnSelection: UIButton!
}

class ViewController: UIViewController {

    var listingDict=[[String:String]]()

    var radioOption:Int?// Only used :: if u are 2. RadioButton Functionality implement

    @IBOutlet weak var tableView: UITableView!
    override func viewDidLoad() {
        super.viewDidLoad()

        tableView.dataSource=self
        tableView.delegate=self

        fillCountryData()
        // Do any additional setup after loading the view.
    }

    func fillCountryData(){
        self.fillJsonData(imgName: "india_flag", countryName: "India")
        self.fillJsonData(imgName: "pakistan_flag", countryName: "Pakistan")
        self.fillJsonData(imgName: "israel_flag", countryName: "Israel")
        self.fillJsonData(imgName: "albania_flag", countryName: "Albania")
        self.fillJsonData(imgName: "america_flag", countryName: "America")
        self.fillJsonData(imgName: "belize_flag", countryName: "Belize")
        self.fillJsonData(imgName: "brunei_flag", countryName: "Brunei")
        self.fillJsonData(imgName: "comoros_flag", countryName: "Comoros")
        self.fillJsonData(imgName: "congo_flag", countryName: "Congo")
        self.fillJsonData(imgName: "ecuador_flag", countryName: "Ecuador")
        self.fillJsonData(imgName: "haiti_flag", countryName: "Haiti")
        self.fillJsonData(imgName: "jamaica_flag", countryName: "Jamaica")
        self.fillJsonData(imgName: "kenya_flag", countryName: "Kenya")
        self.fillJsonData(imgName: "mali_flag", countryName: "Mali")

        self.tableView.reloadData()
    }

    func fillJsonData(imgName:String,countryName:String){
        var dictData=[String:String]()
        dictData["img"]=imgName
        dictData["country"]=countryName
        dictData["check"]="false"
        listingDict.append(dictData)
    }

}

extension ViewController:UITableViewDataSource,UITableViewDelegate{

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return listingDict.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell=tableView.dequeueReusableCell(withIdentifier: "countrySelection") as! countrySelection
        let dictVal=listingDict[indexPath.row]
        cell.lblCountryName.text=dictVal["country"]
        cell.imgFlag.image=UIImage(named:dictVal["img"]!)

        /*//Check Box Functionality
        if dictVal["check"] == "false"{
            cell.btnSelection.setImage(UIImage(named: "checkbox_UnSelect"), for: .normal)
        } else{
            cell.btnSelection.setImage(UIImage(named: "checkbox_Select"), for: .normal)
        }*/

        //RadioButton Functionality
        if radioOption==indexPath.row{
            listingDict[indexPath.row]["check"]="true"
            cell.btnSelection.setImage(UIImage(named: "radioButton_Select"), for: .normal)
        } else{
            listingDict[indexPath.row]["check"]="false"
            cell.btnSelection.setImage(UIImage(named: "radioButton_UnSelect"), for: .normal)
        }

        return cell
    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        /*//CheckBox Functionality
        if listingDict[indexPath.row]["check"]=="true"{
            listingDict[indexPath.row]["check"]="false"
        } else{
            listingDict[indexPath.row]["check"]="true"
        }*/
        //RadioButton Functionality
        print("RadioButton",listingDict)
        if listingDict[indexPath.row]["check"]=="true"{
            radioOption=nil
        } else{
            radioOption=indexPath.row
        }

        self.tableView.reloadData()
    }
}