【问题标题】:Search functionality in a collection view集合视图中的搜索功能
【发布时间】:2018-01-23 23:56:32
【问题描述】:

我的应用中有一个UICollectionViewUICollectionView 填充了来自自定义对象 Employee 的数据。 Employee 对象具有以下属性:

firstName: String
lastName: String
phoneNumber: String
email: String

我想向UICollectionView 添加搜索功能。只能通过名字或姓氏搜索员工。当我使用他们的名字/姓氏搜索特定员工时,如果找到应该在集合视图中显示该特定记录。如果不是,我想显示一个空的集合视图。当没有搜索任何内容时,它应该显示 CollectionView 中的所有记录。

由于Employee 是一个具有许多属性的自定义对象,我不知道如何实现搜索。

我发现一篇文章展示了如何在 UITableView 中实现对 String 数组的搜索:

 class ViewController: UIViewController, UITableViewDataSource, UISearchBarDelegate {

 @IBOutlet weak var tableView: UITableView!
 @IBOutlet weak var searchBar: UISearchBar!

 let data = ["New York, NY", "Los Angeles, CA", "Chicago, IL", "Houston, TX",
    "Philadelphia, PA", "Phoenix, AZ", "San Diego, CA", "San Antonio, TX",
    "Dallas, TX", "Detroit, MI", "San Jose, CA", "Indianapolis, IN",
    "Jacksonville, FL", "San Francisco, CA", "Columbus, OH", "Austin, TX",
    "Memphis, TN", "Baltimore, MD", "Charlotte, ND", "Fort Worth, TX"]

var filteredData: [String]!

override func viewDidLoad() {
    super.viewDidLoad()
    tableView.dataSource = self
    searchBar.delegate = self
    filteredData = data
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "TableCell", for: indexPath) as UITableViewCell
    cell.textLabel?.text = filteredData[indexPath.row]
    return cell
}

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

// This method updates filteredData based on the text in the Search Box
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
    // When there is no text, filteredData is the same as the original data
    // When user has entered text into the search box
    // Use the filter method to iterate over all items in the data array
    // For each item, return true if the item should be included and false if the
    // item should NOT be included
    filteredData = searchText.isEmpty ? data : data.filter { (item: String) -> Bool in
        // If dataItem matches the searchText, return true to include it
        return item.range(of: searchText, options: .caseInsensitive, range: nil, locale: nil) != nil
    }

    tableView.reloadData()
  }
}

但不确定如何在我的情况下实现它。

代码示例对我很有帮助。

提前致谢。

【问题讨论】:

    标签: swift uicollectionview searchbar


    【解决方案1】:

    我假设您也想忽略大小写。试试这个:

    let lowerSearchText = searchText.lowercased()
    filteredData = searchText.isEmpty ? data : data.filter { employee -> Bool in
        return employee.firstName.lowercased().hasPrefix(lowerSearchText) || employee.lastName.lowercased().hasPrefix(lowerSearchText)
    }
    

    您可能希望扩展它以支持其他语言环境(匹配 eé)等。

    【讨论】:

    • 工作就像一个魅力!谢谢
    猜你喜欢
    • 1970-01-01
    • 2012-09-04
    • 1970-01-01
    • 2013-05-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-22
    相关资源
    最近更新 更多