Swift 中的 UiSearchBar 到 UiCollectionView

UiSearchBar to UiCollectionView in Swift

我在屏幕顶部有 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()
    }
}

我也遇到过同样的问题,创建 UISerchBar 而不是 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
    }()

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

searchBar.delegate = 自己 self.definesPresentationContext = 假

searchBar 的自定义函数 这里我们设置 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()
    }
    
}

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