Выбранная строка из каждого раздела UITableView (множественный выбор) - PullRequest
0 голосов
/ 04 сентября 2018

Я использовал просмотр таблицы (сгруппированный).

Так что мне нужно выбрать одну строку в каждом разделе UITableviewSection.

Так что для этого у меня есть просмотр таблицы и одна кнопка отправки. Поэтому мне нужно проверять, когда я нажимаю на кнопку отправки, мне нужно проверить, выбрал ли я по одной строке в каждом разделе, если нет, то показать предупреждение, как не выбранное. Номер раздела. Как проверить?

Это мои данные.

{
    "data":[
              {
               "question": "Gender",
               "options": ["Male","Female"]
              },
              {
               "question": "How old are you",
               "options": ["Under 18","Age 18 to 24","Age 25 to 40","Age 41 to 60","Above 60"]
              },
              {
               "question": "I am filling the Questionnaire for?",
               "options": ["Myself","Mychild","Partner","Others"]
              }
            ]


}

QuestionModel: -

class QuestionListModel: NSObject {
     var selected = false

    var dataListArray33:[NH_OptionsModel] = []


    var id:Int!
    var question:String!
    var buttontype:String!
    var options:[String]?
    var v:String?

      var optionsModelArray:[OptionsModel] = []
    init(dictionary :JSONDictionary) {

        guard   let question = dictionary["question"] as? String,
            let typebutton = dictionary["button_type"] as? String,

                let id = dictionary["id"] as? Int
             else {
                return

        }



        if let options = dictionary["options"] as? [String]{
            print(options)

           print(options)


            for values in options{

                print(values)

                let optionmodel = OptionsModel(values: values)
                self.optionsModelArray.append(optionmodel)

            }


        }


        self.buttontype = typebutton
        self.question = question
        self.id = id
    //   print(self.dataListArray33)
                   }

}

optionModel: -

class OptionsModel: NSObject {

    var isSelected:Bool? = false

  var v:String?
        var values:String?



     init(values:String) {

           self.values = values
           print( self.values)

        }

ViewModel: -

     func numberOfSections(tableView: UITableView) -> Int{
            print((datasourceModel.dataListArray?.count)!)
            return (datasourceModel.dataListArray?.count)!
        }

        func titleForHeaderInSection(atsection section: Int) -> NH_QuestionListModel {
            return datasourceModel.dataListArray![section]
        }

        func numberOfRowsIn(section:Int) -> Int {

            print( datasourceModel.dataListArray?[section].optionsModelArray.count ?? 0)
            return datasourceModel.dataListArray?[section].optionsModelArray.count ?? 0
            // return self.questionsModelArray?[section].optionsModelArray.count ?? 0
        }

        func datafordisplay(atindex indexPath: IndexPath) -> NH_OptionsModel{

            print(datasourceModel.dataListArray![indexPath.section].optionsModelArray[indexPath.row])

            return datasourceModel.dataListArray![indexPath.section].optionsModelArray[indexPath.row]

        }
 func question(answer:String)  {
        print(questions)
        questions.append(answer)
        print(questions )



    }

    func questionlist(answer:String)  {
        print( questionlist )
        questionlist.append(answer)
        print( questionlist )



    }
    func answer(answer:String)  {
      answers.append(answer)
               print(answers)



    }

и, наконец, viewController: -

func numberOfSections(in tableView: UITableView) -> Int {
        return questionViewModel.numberOfSections(tableView: tableView)
    }


    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {


        let identifier = "HeaderCell"

        var headercell: questionheader! = tableView.dequeueReusableCell(withIdentifier: identifier) as? questionheader

        if headercell == nil {
            tableView.register(UINib(nibName: "questionheader", bundle: nil), forCellReuseIdentifier: identifier)
            headercell = tableView.dequeueReusableCell(withIdentifier: identifier) as? NH_questionheader
        }

        headercell.setReviewData(reviews:questionViewModel.titleForHeaderInSection(atsection:section))




        return headercell
    }



    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {

        return 150

    }



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


    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {


        let identifier = "Cell"
        var cell: QuestionListCell! = tableView.dequeueReusableCell(withIdentifier: identifier) as? QuestionListCell

        if cell == nil {
            tableView.register(UINib(nibName: "QuestionListCell", bundle: nil), forCellReuseIdentifier: identifier)
            cell = tableView.dequeueReusableCell(withIdentifier: identifier) as? NH_QuestionListCell
        }
        cell.contentView.backgroundColor = UIColor.clear


        let questionsModel = questionViewModel.titleForHeaderInSection(atsection:indexPath.section)
        print(questionsModel.buttontype)

        questionViewModel.button = questionsModel.buttontype


        cell.setOptions(Options1: questionViewModel.datafordisplay(atindex: indexPath))

         print("Section \(indexPath.section), Row : \(indexPath.row)")


        return cell

    }





    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath){


        print("Section \(indexPath.section), Row : \(indexPath.row)")


        let cell = tableview.cellForRow(at: indexPath) as? NH_QuestionListCell

        let model = questionViewModel.datafordisplay(atindex: indexPath)

        print(model.isSelected)


        cell?.setOptions(OptionsSelected:questionViewModel.datafordisplay(atindex: indexPath))
        print(model.isSelected)
        questionViewModel.isselected = model.isSelected!



        let section = indexPath.section
        let index = indexPath.row
        print(section)
        print(index)



        if !questionViewModel.selectedIndexPaths.contains(indexPath) {

            questionViewModel.selectedIndexPaths.append(indexPath)
            print(questionViewModel.selectedIndexPaths.append(indexPath))


            let questionModel = questionViewModel.titleForHeaderInSection(atsection: section)
            print(questionModel.question)


            questionViewModel.question = questionModel.question
            questionViewModel.questionlist(answer: questionViewModel.question!)


            let cell = tableview.cellForRow(at: indexPath) as? NH_QuestionListCell

            let model = questionViewModel.datafordisplay(atindex: indexPath)
            print(model.values)

            questionViewModel.answer(answer: model.values!)

            let value: Int = questionModel.id
                let string = String(describing: value)
                //let x: Int? = Int(model.id)

            questionViewModel.question_id = string
            questionViewModel.question(answer: questionViewModel.question_id!)

            print(questionModel.id)

            // append the selected index paths
        }       //  if indexPath.section == section {
       //     questionViewModel.indexPath(indexPaths: index)
       // }


            }

func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {




        if let index = questionViewModel.selectedIndexPaths.index(of: indexPath) {
            print(index)
            questionViewModel.selectedIndexPaths.remove(at: index)
        }



}

В соответствии с этим я получил вывод. Но у меня есть действие кнопки в viewcontroller.

@IBAction func forward(_ sender: AnyObject) {
}

В этом действии кнопки мне нужно проверить, выбрал ли я из каждой секции одну строку или нет. Если не показывать предупреждение. Как сделать

мой текущий метод didselect: -

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath){
 let cell = tableview.cellForRow(at: indexPath) as? NH_QuestionListCell

            let model = questionViewModel.datafordisplay(atindex: indexPath)

            print(model.isSelected)


            cell?.setOptions(OptionsSelected:questionViewModel.datafordisplay(atindex: indexPath))
            print(model.isSelected)
            questionViewModel.isselected = model.isSelected!



            let section = indexPath.section
            let index = indexPath.row
            print(section)
            print(index)


            if !questionViewModel.selectedIndexPaths.contains(indexPath) {

                questionViewModel.selectedIndexPaths.append(indexPath)
                print(questionViewModel.selectedIndexPaths.append(indexPath))


                let questionModel = questionViewModel.titleForHeaderInSection(atsection: section)
                print(questionModel.question)


                questionViewModel.question = questionModel.question
                questionViewModel.questionlist(answer: questionViewModel.question!)


                let cell = tableview.cellForRow(at: indexPath) as? NH_QuestionListCell

                let model = questionViewModel.datafordisplay(atindex: indexPath)
                print(model.values)

                questionViewModel.answer(answer: model.values!)

                let value: Int = questionModel.id
                    let string = String(describing: value)
                    //let x: Int? = Int(model.id)

                questionViewModel.question_id = string
                questionViewModel.question(answer: questionViewModel.question_id!)

                print(questionModel.id)

                          }

у меня 3 массива Согласно этому методу didselect: -

ex: -для секции 1: -i выбран 1-й ряд, поэтому данные добавляются, как показано ниже.

questionlist:["How r u?"]
answelist:["fine"]

Но предположим, что мне нужен 2-й индексный путь, поэтому мне нужно удалить предыдущие добавленные данные из массивов и добавить текущие данные. Как показано ниже:

questionlist:["How r u?"]
answelist:["not well"]

И затем для раздела 2: я выбрал первые данные indexpath.row. Затем эти данные добавляются. Так что мне нужно получить, как показано ниже: -

 questionlist:["How r u?","Gender"]
    answelist:["not well","Male"]

Здесь, выбирая, я думаю, что мне нужен второй вариант, затем удалите добавленные данные indexpath.row из массива и покажите как: -

 questionlist:["How r u?","Gender"]
        answelist:["not well","Female"]

Такой способ как настроить?

Ответы [ 4 ]

0 голосов
/ 04 сентября 2018

Шаг 1. Создание глобальной переменной

var selectedIndexPaths = [IndexPath]() 

Шаг 2. Добавление свойства UITableView

tableView.allowsMultipleSelection = true

Шаг 3. Реализация методов делегата

//On Selection
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)      {


        let selectedIndexPathAtCurrentSection = selectedIndexPaths.filter({ $0.section == indexPath.section})

        for indexPath in selectedIndexPathAtCurrentSection {
            tableView.deselectRow(at: indexPath, animated: true)
            if let indexOf = selectedIndexPaths.index(of: indexPath) {
                selectedIndexPaths.remove(at: indexOf)
            }
        }
        selectedIndexPaths.append(indexPath)


}
// On DeSelection
 func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {

    if let index = selectedIndexPaths.index(of: indexPath) {
        selectedIndexPaths.remove(at: index)
    }
}

Шаг 4: Получение выбранных IndexPaths с разделами

@IBAction func forward(sender:Any){

      let totalSections = questionViewModel.numberOfSections(tableView: tableView)


       for section in 0..<totalSections {

        if (selectedIndexPaths.filter({ $0.section == section}).count >= 1) {
            continue
        } else {

            // Show alert
            print("Please select item at",(section))
            return
        }
    }

}
0 голосов
/ 04 сентября 2018

вы можете обновить вашу модель на основе выбора как

"data":[
              {
              "question": "Gender",
              "options": ["Male","Female"],
              "optionSelected": "Male"

              }
              ]

и при отправке проверьте данные для выбора

0 голосов
/ 04 сентября 2018

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

Отметьте примерно так:

var dataSource: [[Any]]!
var tableView: UITableView!

func didSelectRowAt(_ indexPath: IndexPath) {
    guard let selectedPaths = tableView.indexPathsForSelectedRows else { return } // We need to have selected paths
    guard selectedPaths.contains(indexPath) == false else { return } // The same cell being selected

    let previouslySelectedCellIndexPaths: [IndexPath] = selectedPaths.filter { $0.section == indexPath.section && $0 != indexPath } // Getting all selected index paths within this section
    previouslySelectedCellIndexPaths.forEach { tableView.deselectRow(at: $0, animated: true) } // Deselect waht was previously selected
}

/// Will return array of selected objects only if all sections have a selected index
///
/// - Returns: A result array
func getSelectionData() -> [Any]? {
    guard let selectedPaths = tableView.indexPathsForSelectedRows else { return nil } // We need to have selected paths
    guard selectedPaths.count == dataSource.count else { return nil } // This should prevent missing selections assuming all index paths are unique in sections
    return selectedPaths.map { dataSource[$0.section][$0.row] } // Map selected index paths back to objects
}

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

Возможно, вы захотите проверить, все ли разделы уникальны для второго метода, но он не нужен, если всегда используется первый.

0 голосов
/ 04 сентября 2018

Вы можете сохранить выбранный indexPath в массиве. OnClick of submit просто перебрать массив и проверить, что хотя бы один элемент находится в каждом разделе.

К вашему сведению: indexPath также содержит информацию о разделе.

Объявление изменяемого массива и размещение в viewDidLoad.

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
        [anArray addObject:indexPath];

}

при отправке действия следуйте этому, вы можете импровизировать на основе вашего требования

-(void)onSubmitAction{
     [anArray addObject:indexPath];
     NSMutableArray *countOfSection=[[NSMutableArray alloc]init];
    for (NSIndexPath*indexPath in anArray ) {
      if(![anArray containsObject:indexPath.section])
        [countOfSection addObject:indexPath.section];
      }
      if(countOfSection.count == self.tableview.numberOfSections){
    //write your code
      }else{
    // show alert
   }

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