Переключатель с помощью swift4 в iOS - PullRequest
0 голосов
/ 26 апреля 2018

Я хочу создать приложение с несколькими вариантами ответов, в котором я хочу отобразить четыре варианта с одним выбираемым ответом с помощью переключателя, но я не могу понять, как это сделать с помощью массива. Любая помощь будет принята с благодарностью !!!Я прикрепил свой код -

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

Я хочу отобразить словарь 2 вместе с переключателем для выбора опции, вот скриншот моего ожидаемого вывода

enter image description here

Ответы [ 2 ]

0 голосов
/ 26 апреля 2018

Вы можете получить поддержку, например, GitHub Библиотеки:

  1. https://github.com/DavydLiu/DLRadioButton
  2. https://github.com/onegray/RadioButton-ios
  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

Или, если вы хотите сделать это программно, используя UIButton Дайте мне знать, что я могу поделиться с вами кодом.

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

Вам нужно взять групповые розетки всех ваших UIButton и сделать некоторую логику, подобную этой, если вы предпочитаете делать это программно. Или вы также можете создать массив для хранения идентификатора выбранного тега кнопки. И используйте как, чтобы выбрать и отменить выбор UIButton с этой логикой

Надеюсь, эта помощь.

Простая демонстрация для радио кнопки

Демонстрационный код можно загрузить здесь Демо-кнопка радио

0 голосов
/ 26 апреля 2018

Если вы используете просмотр таблицы для параметров, сохраните состояние переключателя каждой ячейки в массиве моделей.После использования нажмите на переключатель, измените состояние переключателя и перезагрузите просмотр таблицы.Пользовательский интерфейс будет лучшим способом реализации.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...