Swift:让 SearchBar 搜索两个部分,而不是将它们合并 [英] Swift: Have SearchBar search through both sections and not combine them

查看:24
本文介绍了Swift:让 SearchBar 搜索两个部分,而不是将它们合并的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 Swift 3,该应用程序是一个使用 PHP 和 JSON 从 MYSQL 数据库读取数据的博客阅读器.

Using Swift 3, the app is a blog reader reading from a MYSQL database using PHP and JSON.

目前我的 SearchBar 没有做我想要的,我让它在我的 mainArray(第 1 部分)中使用全部"范围进行搜索.当它被过滤时,被过滤的对象被移动到filteredArray.我同时这样做是因为我不知道如何让它做我想做的事.

Currently my SearchBar is not doing what I want, I have it searching in my mainArray (section 1) with the 'All' scope. As it's being filtered the objects that are being filtered are moved to filteredArray. I did this in the mean time because I can not figure out how to make it do what I want.

它应该做的是,当用户搜索一个对象时,我希望该对象显示在 mainArray 或 followArray 中,而不是将它移动到不同的数组,这样它就不会合并.基本上过滤 tableview 并且不删除任何部分或组合任何对象,因为它会混淆用户不知道对象位于哪个部分,当然要确保范围栏正常工作.

What it's supposed to do is this, when the user is searching for an object, I want the object to show up wether it's in mainArray or followedArray and not move it to a different array so its doesn't combine. Basically filter the tableview and not remove any sections or combine any objects as it will confuse the user by not knowing which section the object was in, and of course make sure the scope bar is working properly.

学习如何实现搜索栏,以便您在我尝试更进一步时看到我的问题.谢谢!

Learning how to implement a search bar so you can see my trouble when I try to take it a level further. Thank you!

搜索栏 &范围代码

SearchBar & Scope code

let searchController = UISearchController(searchResultsController: nil)

override func viewDidLoad() {
    // Search Bar
    searchController.searchResultsUpdater = self
    searchController.dimsBackgroundDuringPresentation = false
    definesPresentationContext = true
    myTableView.tableHeaderView = searchController.searchBar
    searchController.searchBar.backgroundColor = UIColor.white
    searchController.searchBar.barTintColor = UIColor.white

    // Scope Bar
    searchController.searchBar.scopeButtonTitles = ["All", "Released", "Unreleased", "Free"]
    searchController.searchBar.delegate = self
}

// Title for Header
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {

    if !(searchController.isActive && searchController.searchBar.text != "") {

        if section == 0 {
            return "Followed Blogs"
        }
        else {
            return "All Blogs"
        }
    }
    return "Filtered Blogs"
}

// Number of Rows in Section
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

    if !(searchController.isActive && searchController.searchBar.text != "") {

        if section == 0 {

            return followedArray.count
        }
        else if (section == 1) {

            return mainArray.count
        }
    }
    return filteredArray.count
}

// Number of Sections
func numberOfSections(in tableView: UITableView) -> Int {

    if !(searchController.isActive && searchController.searchBar.text != "") {

        return 2
    }
    return 1
}

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

    let CellIdentifier = "Cell"
    var cell = tableView.dequeueReusableCell(withIdentifier: CellIdentifier) as! CustomCell

    if cell != cell {
        cell = CustomCell(style: UITableViewCellStyle.default, reuseIdentifier: CellIdentifier)
    }

    // Configuring the cell
    var blogObject: Blog

    if !(searchController.isActive && searchController.searchBar.text != "") {
        if indexPath.section == 0 {
            blogObject = followedArray[indexPath.row] 
            cell.populateCell(blogObject, isFollowed: true, indexPath: indexPath, parentView: self)
        }
        else if indexPath.section == 1 {
            blogObject = mainArray[indexPath.row] 
            cell.populateCell(blogObject, isFollowed: false, indexPath: indexPath, parentView: self)
        }
    }
    else {
        blogObject = filteredArray[indexPath.row] 
        cell.populateCell(blogObject, isFollowed: false, indexPath: indexPath, parentView: self)
    }

    return cell
}

// SEARCH BAR: Filtering Content
func filterContentForSearchText(searchText: String, scope: String = "All") {

    filteredArray = mainArray.filter { Blog in

        let categoryMatch = (scope == "All") || (Blog.blogType == scope)

        return categoryMatch && (Blog.blogName.lowercased().contains(searchText.lowercased()))
    }
    myTableView.reloadData()
}

// SEARCH BAR: Updating Results
func updateSearchResults(for searchController: UISearchController) {

    filterContentForSearchText(searchText: searchController.searchBar.text!)
}

// SEARCH BAR: Scope
func searchBar(_ searchBar: UISearchBar, selectedScopeButtonIndexDidChange selectedScope: Int) {

    filterContentForSearchText(searchText: searchBar.text!, scope: searchBar.scopeButtonTitles![selectedScope])
}

// SEARCH BAR: Updating Scope
func updateSearchResultsForSearchController(searchController: UISearchController) {

    let searchBar = searchController.searchBar
    let scope = searchBar.scopeButtonTitles![searchBar.selectedScopeButtonIndex]
    filterContentForSearchText(searchText: searchController.searchBar.text!, scope: scope)
}

// Deallocating Search Bar
deinit{
    if let superView = searchController.view.superview {
        superView.removeFromSuperview()
    }
}

推荐答案

现在您创建一个数组 (filteredArray) 并假设您在搜索时有 1 个部分.

Right now you create a single array (filteredArray) and assume you have 1 section when searching.

我会删除这个假设.

在您的 filterContentForSearchText 方法中,创建一个数组数组(其中每个内部数组代表一个部分).

Inside your filterContentForSearchText method, create an array of arrays (where each inner array represents a section).

然后更新所有表视图数据源方法以处理该数组数组以获得正确的值.

Then update all of your table view data source methods to work with that array of arrays to get the proper values.

首先,将您的 filteredArray 声明更新为数组数组.

First, update your declaration of filteredArray to be an array of arrays.

现在更新你的表格视图方法:

Now update your table view methods:

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    if !(searchController.isActive && searchController.searchBar.text != "") {
        if section == 0 {
            return followedArray.count
        } else {
            return mainArray.count
        }
    } else {
        return filteredArray[section].count
    }
}

// Number of Sections
func numberOfSections(in tableView: UITableView) -> Int {
    if !(searchController.isActive && searchController.searchBar.text != "") {
        return 2
    } else {
        return filteredArray.count
    }
}

// CellForRowAt indexPath
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let CellIdentifier = "Cell"
    var cell = tableView.dequeueReusableCell(withIdentifier: CellIdentifier) as! CustomCell

    if cell != cell {
        cell = CustomCell(style: UITableViewCellStyle.default, reuseIdentifier: CellIdentifier)
    }

    // Configuring the cell
    var blogObject: Blog

    if !(searchController.isActive && searchController.searchBar.text != "") {
        if indexPath.section == 0 {
            blogObject = followedArray[indexPath.row] 
            cell.populateCell(blogObject, isFollowed: true, indexPath: indexPath, parentView: self)
        } else {
            blogObject = mainArray[indexPath.row] 
            cell.populateCell(blogObject, isFollowed: false, indexPath: indexPath, parentView: self)
        }
    } else {
        blogObject = filteredArray[indexPath.section][indexPath.row] 
        cell.populateCell(blogObject, isFollowed: false, indexPath: indexPath, parentView: self)
    }

    return cell
}

最后更新filterContentForSearchText方法:

func filterContentForSearchText(searchText: String, scope: String = "All") {
    let filteredFollowed = followedArray.filter { Blog in
        let categoryMatch = (scope == "All") || (Blog.blogType == scope)

        return categoryMatch && (Blog.blogName.lowercased().contains(searchText.lowercased()))
    }

    let filteredMain = mainArray.filter { Blog in
        let categoryMatch = (scope == "All") || (Blog.blogType == scope)

        return categoryMatch && (Blog.blogName.lowercased().contains(searchText.lowercased()))
    }

    filteredArray = [ filteredFollowed, filteredMain ]

    myTableView.reloadData()
}

这篇关于Swift:让 SearchBar 搜索两个部分,而不是将它们合并的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆