The best way to use checkbox - IOS swift

半世苍凉 提交于 2019-12-31 10:56:07

问题


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?

I will use checkboxes in forms and for settings purpose.

Thanks.


回答1:


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

For Storyboard:

  1. Set your button's selected image:

  2. Set your button's default image:

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
}



回答2:


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



回答3:


You can use the approach below which will most helpful: In your StoryBoard or ViewDidLoad assign the image for UIButton:

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

After this in your @IBAction Method just implement the following code:

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

This will do the trick.




回答4:


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



回答5:


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.

Tested Code

  • Swift 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()
    }
}


来源:https://stackoverflow.com/questions/41344895/the-best-way-to-use-checkbox-ios-swift

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!