-2

I want to create multiple choice question app in which i want to display four options with one selectable answer using radio button but I am not able to understand how to do it using array , Any help will be appreciated !!! I herreby attached my code --

import UIKit

class ViewController: UIViewController,UITableViewDataSource,UITableViewDelegate {

    @IBOutlet weak var titleLabel: UILabel!
    @IBOutlet weak var topicLabel: UILabel!

    @IBOutlet weak var tableView: UITableView!

    var dictionary1 = [Int:String]()
    var dictionary2 = [Int:Array<String>]()




    override func viewDidLoad() {

         dictionary1 = [0:"Whether you have experienced Pricking-pain, Desquamation,itching or dry skin sensation during seasonal alternate.", 1:"Whether your skin apt to flush( Redness) in hot humid environment ", 2:"Whether your skin has multiple disernible dilated capillaries.", 3:"whether you have once been diagnosed atopic dermatitis or seborrheic dermatitis."]

         dictionary2 = [0:["Never","Seldom","Usually","Always"],1:["Never","Seldom","Usually","Always"],2:["Never","Seldom","Usually","Always"],3:["Yes", "No"]]


        titleLabel.text = "Fill Skin Type Survey Form "
        titleLabel.textColor = UIColor.black

        topicLabel.text = "Are You with sensitive skin type ?"
        topicLabel.font = UIFont.boldSystemFont(ofSize: 18)

        let homeNib = UINib(nibName: "DemoTableViewCell", bundle: nil)
        self.tableView.register(homeNib, forCellReuseIdentifier: "DemoTableViewCell")


    }


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

        func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
            let cell:DemoTableViewCell = self.tableView.dequeueReusableCell(withIdentifier: "DemoTableViewCell", for: indexPath) as! DemoTableViewCell

            // FOR FIRST DICTIONARY


            cell.questionLabel.text = dictionary1[indexPath.row]
            cell.questionLabel.font = UIFont.boldSystemFont(ofSize: 16)

            // FOR SECOND DICTIONARY


            cell.optionsLabel.text = dictionary2[indexPath.row]?.joined(separator: "    ")

            return cell
        }

        func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
            return UITableViewAutomaticDimension
        }

        func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
            return 350.0

I want to display dictionary 2 along with radio button for selecting an option , here is screenshot of my expected output

enter image description here

Sudhir
  • 61
  • 1
  • 2
  • 11
  • RadioButton is not an available UI-component in iOS' UIKit. You'll need to implement it yourself, find a third-party component or rethink your UI... – T. Benjamin Larsen Apr 26 '18 at 06:22
  • Maybe this helps for your problem: https://stackoverflow.com/questions/29117759/how-to-create-radio-buttons-and-checkbox-in-swift-ios – Teetz Apr 26 '18 at 06:24
  • Although your question seems to be off-topic, I prefer to help you with this issue... iOS does *not* natively has a radio button component, you would need to create it by your self, or as a better option you could get the help of one of the libraries, I would suggest https://github.com/DavydLiu/DLRadioButton, it works fine with me. – Ahmad F Apr 26 '18 at 06:26
  • In one of the app, I used UITableView for showing options. Each cell (complete cell) represented an option. didSelectRow acted as the selected option. – Nitish Apr 26 '18 at 06:27
  • Is it a duplicate of: https://stackoverflow.com/questions/29117759/how-to-create-radio-buttons-and-checkbox-in-swift-ios? – Ahmad F Apr 26 '18 at 06:28
  • 1
    Possible duplicate of [How to create radio buttons and checkbox in swift (iOS)?](https://stackoverflow.com/questions/29117759/how-to-create-radio-buttons-and-checkbox-in-swift-ios) – DaniEll Apr 26 '18 at 06:35

3 Answers3

4

You can get the support from so many GitHub Libraries:

  1. https://github.com/DavydLiu/DLRadioButton
  2. https://github.com/onegray/RadioButton-ios (No longer actively maintained)
  3. https://github.com/alhazmy13/RadioButtonSwift3
  4. https://github.com/xxi511/radioButton-swift
  5. https://github.com/VenkateshYadavP/PVRadioButton
  6. https://github.com/thegoal/ISRadioButton

Or else if u want to do that programmatically using UIButton lemme know i can share the code with you.

@IBAction func btnRadioCategoryClicked(_ sender: UIButton) {
    for button in btnALLTerritory {
        if sender.tag == button.tag{
            button.isSelected = true;
            button.setImage(#imageLiteral(resourceName: "ic_Radio_filled"), for: .normal)
        }else{
            button.isSelected = false;
            button.setImage(#imageLiteral(resourceName: "ic_Radio_Empty"), for: .normal)
        }                                                                                                                                                                                                                                          
    }
}

You need to take the Group Outlets of all your UIButton and make some logic like this if you prefer to do that programmatically. Or also you can make an array to store the id of Selected button tag. And use like to select and Unselect a UIButton with that logic

Hope this help.

Simple Demo for Radio Button

You can download the demo code from here Demo Of Radio Button

Abhirajsinh Thakore
  • 1,806
  • 2
  • 13
  • 23
  • 2
    Link only answers should be avoided. – Nitish Apr 26 '18 at 06:24
  • 2
    @Nitish Appreciated your notice, have added some other ideas in this – Abhirajsinh Thakore Apr 26 '18 at 06:27
  • I have created dictionary for showing options , how to create radio button using dictionary , my dictionary look like this - dictionary2 = [0:["Never","Seldom","Usually","Always"],1:["Never","Seldom","Usually","Always"],2:["Never","Seldom","Usually","Always"],3:["Yes", "No"]] , where Int is key for question which is stored in another dictionary – Sudhir Apr 26 '18 at 06:29
  • @Sudhir I will prefer you to use some of the git Libraries i provided you. That would make your task easy. Or else assign a tag to each Button. And every-time you click on the button, manage an [Int] type and check if the tag already available then remove it, else use it – Abhirajsinh Thakore Apr 26 '18 at 06:32
  • @Sudhir added a sample code for you, Hope that helps you – Abhirajsinh Thakore Apr 26 '18 at 06:42
  • @AbhirajsinhThakore Thanks , I want four radio buttons with given options in the dictionary against the questions , I am quite new to swift , So not able to understand how to do it !!! – Sudhir Apr 26 '18 at 06:53
  • @Sudhir so can i know, in which case you want to make the condition.? like in which case it should be selected in which not.? – Abhirajsinh Thakore Apr 26 '18 at 06:59
  • @AbhirajsinhThakore It is just like a Form in which a question is asked and you have four option for that question , i have created dictionary of [int,string] for question and dictionary of [int ,array] for option , and now i want to display the question along withe option but the option should be displayed along with radio type button for selection !!! – Sudhir Apr 26 '18 at 07:05
  • I guess this would require a complex logic. I would suggest you give a tag to each button. and then in it is selected, capture the tag of that button and compare like if tag == 1 then never, if tag ==2 seldom, if tag ==3 usually and so on. – Abhirajsinh Thakore Apr 26 '18 at 07:10
  • @Sudhir Have you been able to solve this scenario?Even i have a similar scenario right now.I tried using DLRadioButton,but it did not recognise all buttons inside tableview.Tried the solution given by abhirajsinh too, but the problem is the image of the button is changing when the tableview is scrolled. – Saranya Oct 06 '20 at 09:31
1

By referring Abhirajsinh solution, I have created two buttons in interface and connected to controller. Make sure that you have changes tag value in attribute for button1(Tag = 0) and button2(Tag = 1). Also remove selected images in interface for each button.

class AddWorkExperienceViewController: UIViewController {

//    MARK: - IBOutlets
    var btnALLTerritory = [UIButton]()

    @IBOutlet weak var doButton: UIButton!
    @IBOutlet weak var dontButton: UIButton!

    override func viewDidLoad() {
        super.viewDidLoad()

        btnALLTerritory = [doButton,dontButton]
    }


//    MARK: - Actions

    @IBAction func btnRadioCategoryClicked(_ sender: UIButton) {
        for button in btnALLTerritory {
            if sender.tag == button.tag{
                button.isSelected = true;
                button.setImage(#imageLiteral(resourceName: "radioButton-selected"), for: .normal)
            }else{
                button.isSelected = false;
                button.setImage(#imageLiteral(resourceName: "radioButton-unselected"), for: .normal)
            }
        }
    }

}
prachit
  • 365
  • 3
  • 10
0

If you are using tableview for options then save the state of the each cell radio button in Model Array. Once use click on radio button, change the state of radio button and reload table view. Custom UI will be the best way to implement.

Manish Mahajan
  • 2,062
  • 1
  • 13
  • 19