使用嵌入在TableView Cell Swift 5中的CollectionView值实现TableView值的搜索功能

问题描述

我在tableview单元内实现了collectionview单元,每个表视图单元都有一个 title和4个collectionview单元。我已经实现了使用文本框作为搜索栏的搜索功能。当我开始在文本文件中键入内容时,重新加载了tableview,并且可以看到搜索结果,即tablview单元格中具有匹配标题的单元格出现了,但是collectionview单元格保持不变,但它们并未按照其tableview单元格进行更改。我对此感到困惑,无法达到预期的效果

下面是我用于搜索和加载数据的代码

SearchViewController

var search: String = ""
var AllData = [TableTitle]()
var SearchData = [TableTitle]()

var tableViewTitleArray = [TableTitle]()
var collectionViewArray = [CollectionData]()

override func viewDidLoad() {
    super.viewDidLoad()
    self.searchTextField.delegate = self
    self.tableView.delegate = self
    self.tableView.dataSource = self
} 

API调用

func API() {
    let tableTitle = try JSONDecoder().decode(Initial.self,from: data)  
    let titleList: [TableTitle] = tableTitle.data
    self.tableDataArray = titleList
    
    self.AllData = titleList
    self.SearchData = self.AllData
    
     for i in 0..<self.tableViewTitleArray.count {
      let title = titleList[i].title
      self.titleArray.append(title)
      let collectionData: [CollectionData] = titleList[i].collectionData
      self.collectionViewArray = collectionData
      self.tableView.reloadData()
}

TableView委托

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

 func tableView(_ tableView: UITableView,cellForRowAt indexPath: IndexPath) -> 
   UITableViewCell {
       let titleCell = tableView.dequeueReusableCell(withIdentifier: "Cell",for: indexPath) as! TitleTableViewCell
       
       let Data : TableTitle = SearchData[indexPath.row]

        titleCell.titleLabel.text = Data.title
        titleCell.collectionArray = self.collectionViewArray
        titleCell.collectionView.reloadData()

        return titleCell
   }

搜索功能

 func textField(_ textField: UITextField,shouldChangeCharactersIn range: NSRange,replacementString string: String) -> Bool{
    if string.isEmpty {
       search = String(search.dropLast())
   } else {
       search=textField.text!+string
   }
    print("search text: ",search)
    if search.count > 0 {
    self. SearchData = self.AllData.filter({ (result) -> Bool in
        return result.title.range(of: search,options: .caseInsensitive) != nil
    })
    print("search data: ",self.SearchData)
    } else {
    print("Else")
    self. SearchData = self.AllData
    }
    self.tableView.reloadData()
    return true

}

注意:我刚刚添加了必需的代码,并删除了此问题不需要的代码

任何帮助将不胜感激。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)