Search Controller with multiple section in UITableView

喜夏-厌秋 提交于 2019-12-04 11:44:21

One way for you to is when you filter work with single section, so first change your filteredshops like this way.

func filteredshops(_ searchText: String, scope: String = "All") {
    let filteredShopsA = itemA.filter({ item in
        if let name = item["itemName"], let query = searchController.searchBar.text {
            return name.range(of: query, options: [.caseInsensitive, .diacriticInsensitive]) != nil
        }
        return false
    })
    let filteredShopsB = itemB.filter({ item in
        if let name = item["itemName"], let query = searchController.searchBar.text {
            return name.range(of: query, options: [.caseInsensitive, .diacriticInsensitive]) != nil
        }
        return false
    })
    let filteredShopsC = itemC.filter({ item in
        if let name = item["itemName"], let query = searchController.searchBar.text {
            return name.range(of: query, options: [.caseInsensitive, .diacriticInsensitive]) != nil
        }
        return false
    })
    filteredShops = filteredShopsA + filteredShopsB + filteredShopsC 
    tableView.reloadData()
}

Now with tableView method make change like this way.

func numberOfSections(in tableView: UITableView) -> Int {
    if searchController.isActive {
        return 1
    }
    return self.sections.count
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    if searchController.isActive {
        return filteredShops.count
    }   
    switch (section) {
    case 0: 
       return itemsA.count
    case 1: 
       return itemsB.count
    default: 
       return itemsC.count
    }
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "StoreCell") as! UITableViewCell
    if searchController.isActive {
        //Access filteredShops array 
    }  
    else {  
        switch (indexPath.section) {
        case 0: 
            //Access itemsA[indexPath.row]
        case 1: 
            //Access itemsB[indexPath.row]
        default: 
            //Access itemsC[indexPath.row]
        }
    }
    return cell
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!