Swift 中的 UiSearchBar 到 UiCollectionView

Posted

技术标签:

【中文标题】Swift 中的 UiSearchBar 到 UiCollectionView【英文标题】:UiSearchBar to UiCollectionView in Swift 【发布时间】:2020-10-16 14:30:02 【问题描述】:

我在屏幕顶部有 2 个标签。每个页面都包含collectionView。而且我必须在collectionView 的顶部创建一个searchBar。我希望它看起来像在设置应用程序中(向下滚动时出现,向上滚动时消失)。 这是我用于搜索组件的代码。但由于我在页面内没有导航栏,所以它没有显示。

请帮我在 tabBar 和 collectionView 之间进行搜索。

    import UIKit

    class ViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate, UISearchControllerDelegate, UISearchBarDelegate, UISearchResultsUpdating 

    var filtered:[String] = []
    var searchActive : Bool = false
    let searchController = UISearchController(searchResultsController: nil)

    @IBOutlet weak var collectionView: UICollectionView!

    var items = ["Apple", "Orange", "Apple", "Orange", "Apple", "Orange", "Apple", "Orange", "Apple", "Orange", "Apple", "Orange"]

    override func viewDidLoad() 
        super.viewDidLoad()

        collectionView.delegate = self
        collectionView.dataSource = self

        self.searchController.searchResultsUpdater = self
        self.searchController.delegate = self
        self.searchController.searchBar.delegate = self
        self.searchController.hidesNavigationBarDuringPresentation = false
        self.searchController.dimsBackgroundDuringPresentation = true
        self.searchController.obscuresBackgroundDuringPresentation = false
        searchController.searchBar.placeholder = "Search..."
        searchController.searchBar.sizeToFit()
        searchController.searchBar.becomeFirstResponder()
        self.navigationItem.titleView = searchController.searchBar

        self.definesPresentationContext = true
        self.searchController.searchBar.placeholder = "Search for Items"

    

    override func didReceiveMemoryWarning() 
        super.didReceiveMemoryWarning()
    

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int 

            if searchActive 
                return filtered.count
            
            else
            
                return items.count
            
    

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell 
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! CollectionViewCell

        cell.contentView.layer.cornerRadius = 7.0
        cell.contentView.layer.borderWidth = 1.0
        cell.contentView.layer.borderColor = UIColor.clear.cgColor
        cell.contentView.layer.masksToBounds = false
        cell.layer.cornerRadius = 7.0

        return cell
    

    func searchBarCancelButtonClicked(_ searchBar: UISearchBar) 
        searchActive = false
        self.dismiss(animated: true, completion: nil)
    

    func updateSearchResults(for searchController: UISearchController)
    
        let searchString = searchController.searchBar.text

        filtered = items.filter( (item) -> Bool in
            let countryText: NSString = item as NSString

            return (countryText.range(of: searchString!, options: NSString.CompareOptions.caseInsensitive).location) != NSNotFound
        )

        collectionView.reloadData()
    

    func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) 
        searchActive = true
        collectionView.reloadData()
    

    func searchBarSearchButtonClicked(_ searchBar: UISearchBar) 
        searchActive = false
        collectionView.reloadData()
    

    func searchBarBookmarkButtonClicked(_ searchBar: UISearchBar) 
        if !searchActive 
            searchActive = true
            collectionView.reloadData()
        

        searchController.searchBar.resignFirstResponder()
    

【问题讨论】:

【参考方案1】:

我也遇到了同样的问题,创建 UISercBar 而不是 UISearchController 是实现目标的最佳方式。

这里是设置 UISearchBar 与 UISearchBarController 功能完全相同的示例:

设置搜索栏

let searchBar: UISearchBar = 
       
        let searchBar = UISearchBar()
        searchBar.tintColor = UIColor.black.withAlphaComponent(1.0)
        searchBar.placeholder = "Search for exercise"
        searchBar.backgroundColor = UIColor.clear
        searchBar.barTintColor = UIColor.clear
        searchBar.searchBarStyle = .minimal
        searchBar.returnKeyType = .search
        searchBar.showsCancelButton = false
        searchBar.showsBookmarkButton = false
        searchBar.sizeToFit()
        
        return searchBar
    ()

设置它的委托并且不要忘记将definePresentationContext设置为false,否则searchBar不会出现

searchBar.delegate = self self.definesPresentationContext = false

搜索栏的自定义函数 我们在这里设置 SearchBar 的行为

extension YourViewController: UISearchBarDelegate 
    
    func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) 
        searchActive = true
        self.searchBar.showsCancelButton = true
        self.collectionView.reloadData()
    
    
    func searchBarCancelButtonClicked(_ searchBar: UISearchBar) 
        self.searchBar.text = ""
        self.filtered = []
        searchActive = false
        self.searchBar.showsCancelButton = false
        self.searchBar.endEditing(true)
        self.dismiss(animated: true, completion: nil)
        self.collectionView.reloadData()
    
    
    func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) 
        
        if searchBar.text! == " "  
            filtered = exercises
            collectionView.reloadData()
         else 
        
        filtered = exercises.filter( (item) -> Bool in
            
            return (item.exerciseNameLabel?.localizedCaseInsensitiveContains(String(searchBar.text!)))!
            
            )
        
        collectionView.reloadData()
        
        
    
    
    func searchBarSearchButtonClicked(_ searchBar: UISearchBar) 
        collectionView.reloadData()
    
    

希望对您的问题有所帮助:)

【讨论】:

以上是关于Swift 中的 UiSearchBar 到 UiCollectionView的主要内容,如果未能解决你的问题,请参考以下文章

如何在swift 3中过滤UISearchBar中的数组模型

NavigationItem + UISearchBar 与 Swift

swift 扩展到UISEARCHBAR。更改放大玻璃,x按钮和占位符的颜色。

UISearchbar 在 Swift 4 中使用 UItextfield

Swift:UISearchBar,通过 NSPredicate 名字或姓氏查找 Person

如何将 UiSearchBar 的背景颜色更改为黑色-SWIFT