首页 > 解决方案 > TableView中SearchController过滤问题

问题描述

我有下一个模型:

struct HashTags {
    var title = ""
    var tags = [String]()
}

我尝试使用 UISearchController 在标签数组中搜索文本。

我在 TableViewController 中实现了 UISearchController:

class TagsController: UITableViewController {
    
    var hashtags = [HashTags]()
    var filtered = [HashTags]()
    
    let searchController = UISearchController(searchResultsController: nil)

    var searchBarIsEmpty: Bool {
        guard let text = searchController.searchBar.text else { return false }
        return text.isEmpty
    }
    
    var isFiltering: Bool {
        return searchController.isActive && !searchBarIsEmpty
    }

    override func viewDidLoad() {
        super.viewDidLoad()
                
        searchController.searchResultsUpdater = self
        searchController.obscuresBackgroundDuringPresentation = false
        searchController.searchBar.placeholder = "Search"
        navigationItem.searchController = searchController
        definesPresentationContext = true
    }

    override func numberOfSections(in tableView: UITableView) -> Int {
        if isFiltering {
            return filtered.count
        }

        return hashtags.count
    }
    
    override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        if isFiltering {
            return filtered[section].title
        }

        return hashtags[section].title
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if isFiltering {
            return filtered[section].tags.count
        }
        return 1
    }

    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "Tags", for: indexPath)
        
        var item = HashTags()

        if isFiltering {
            item = filtered[indexPath.section]
        } else {
            item = hashtags[indexPath.section]
        }


        let tags = item.tags
    
        cell.textLabel?.text = tags.joined(separator: ", ")

        return cell
    }

}

extension TagsController: UISearchResultsUpdating {
    
    func updateSearchResults(for searchController: UISearchController) {
        filterContentForSearchText(searchController.searchBar.text!)
    }
    
    func filterContentForSearchText(_ searchText: String) {
        filtered = hashtags.filter({ (hashtag: HashTags) -> Bool in
            return hashtag.tags.contains(searchText.lowercased())
        })
        tableView.reloadData()
    }
    
}

但它不能正常工作,当我开始输入文本时,我会收到空​​白屏幕。我需要 UISearchController 正常工作并在 HashTags 标签数组中搜索文本,显示正确的部分和行数。

标签: iosswiftuitableviewuisearchcontroller

解决方案


推荐阅读