быстрый просмотр таблицы с разделами не может использовать панель поиска - PullRequest
2 голосов
/ 29 октября 2019

Я создал таблицу с помощью панели поиска. Мой набор данных выглядит следующим образом:

    var data : [[ContactObject]] = []

Все работает хорошо, но если я пытаюсь найти, это не работает. Вот мой метод поиска:

  func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
    filteredGroups = self.data[1].filter({(bo:  ContactObject ) -> Bool in
               return bo.name!.lowercased().contains(searchText.lowercased())
            })
    filteredUsers = self.data[2].filter({(bo:  ContactObject ) -> Bool in
        return bo.name!.lowercased().contains(searchText.lowercased())
     })
    self.filteredData.append(self.myStories)
    self.filteredData.append(self.filteredGroups  )
    self.filteredData.append(self.filteredUsers)
     collectionView.reloadData()
 }

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

 func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    if !isFiltering(){
    if data[indexPath.section][indexPath.row].name == "Freunde" || data[indexPath.section][indexPath.row].name == "Interessen (öffentlich)"{
       var cell1 = tableView.dequeueReusableCell(withIdentifier: "selectStory", for: indexPath) as! StorySelectionTableViewCell

        cell1.label.text = data[indexPath.section][indexPath.row].name
        cell1.select.setOn(false, animated: true)
        cell1.select.tag = indexPath.row
        cell1.select.addTarget(self, action: #selector(handleSwitch), for: .valueChanged)
        return cell1
    }

        var cell = tableView.dequeueReusableCell(withIdentifier: "contactCell", for: indexPath) as! ContactsTableViewCell
        cell.select.tag = indexPath.row
        cell.thumb.layer.masksToBounds = false
        cell.thumb.layer.cornerRadius = cell.thumb.frame.height/2
        cell.thumb.clipsToBounds = true
        cell.name.text =  data[indexPath.section][indexPath.row].name
        cell.select.addTarget(self, action: #selector(handleButtonPress), for: .touchDown)
        if data[indexPath.section][indexPath.row].imageUrl != "" && data[indexPath.section][indexPath.row].imageUrl != nil{

            let url = URL(string:  data[indexPath.section][indexPath.row].imageUrl!)
            cell.thumb.kf.setImage(with: url)

                }
        return cell

    }else{



        if filteredData[indexPath.section][indexPath.row].name == "Freunde" || filteredData[indexPath.section][indexPath.row].name == "Interessen (öffentlich)"{
                var cell1 = tableView.dequeueReusableCell(withIdentifier: "selectStory", for: indexPath) as! StorySelectionTableViewCell

                 cell1.label.text = filteredData[indexPath.section][indexPath.row].name
                 cell1.select.setOn(false, animated: true)
                 cell1.select.tag = indexPath.row
                 cell1.select.addTarget(self, action: #selector(handleSwitch), for: .valueChanged)
                 return cell1
             }

                 var cell = tableView.dequeueReusableCell(withIdentifier: "contactCell", for: indexPath) as! ContactsTableViewCell
                 cell.select.tag = indexPath.row
                 cell.thumb.layer.masksToBounds = false
                 cell.thumb.layer.cornerRadius = cell.thumb.frame.height/2
                 cell.thumb.clipsToBounds = true
                 cell.name.text =  filteredData[indexPath.section][indexPath.row].name
                 cell.select.addTarget(self, action: #selector(handleButtonPress), for: .touchDown)
                 if data[indexPath.section][indexPath.row].imageUrl != "" && data[indexPath.section][indexPath.row].imageUrl != nil{

                     let url = URL(string:  filteredData[indexPath.section][indexPath.row].imageUrl!)
                     cell.thumb.kf.setImage(with: url)

                         }
                 return cell

    }


}

и мой numbersOfRowsInSection следующим образом:

   func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    if isFiltering(){
        return filteredData[section].count
    }
return data[section].count
}

результат не имеет значения, какое слово i 'После ввода текста мой третий раздел (self.filteredUsers) всегда пуст, а self.filteredGroups всегда завершается.

1 Ответ

0 голосов
/ 29 октября 2019

Это всего лишь предположение, но я думаю, вам не следует добавлять к filteredData здесь:

self.filteredData.append(self.myStories)
self.filteredData.append(self.filteredGroups  )
self.filteredData.append(self.filteredUsers)

Это сделает filteredData длиннее и длиннее, а cellForRowAt использует только первые три элемента. Вместо этого вы должны заменить весь массив тремя подмассивами:

filteredData = [myStories, filteredGroups, filteredUsers]

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

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