当我运行我的项目时,搜索栏没有出现在 UICollectionView 的标题中

Kuk*_*toA 1 uisearchbar ios uicollectionview swift

我应该如何处理这个问题?我不知道如何将搜索栏与 UICollectionView 正确集成。请帮助我理解这个问题。

PS 我的语言是 Swift

我在 Interface Builder 中的视图 [1]

我运行项目时的看法 [2]

导入 UIKit

类 MainViewController: UICollectionViewController {

override func viewDidLoad() {
    super.viewDidLoad()
}



override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return 14
}

override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "TrendingGifCell", for: indexPath)
    return cell
}
Run Code Online (Sandbox Code Playgroud)

}

0nd*_*re_ 5

试试下面的代码,它应该可以解决你的问题:

    class MainViewController: UICollectionViewController,UISearchControllerDelegate, UISearchBarDelegate, UISearchResultsUpdating {

    var searchController : UISearchController!

    override func viewDidLoad() {
        super.viewDidLoad()


        //Search at the top
        self.searchController = UISearchController(searchResultsController:  nil)

        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.becomeFirstResponder()

        self.navigationItem.titleView = searchController.searchBar



}



    override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return 14
    }

    override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "TrendingGifCell", for: indexPath)
        return cell
    }

func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
    self.dismiss(animated: true, completion: nil)
}

func updateSearchResults(for searchController: UISearchController)
{
    print("updating") 
}


    }
Run Code Online (Sandbox Code Playgroud)

让我知道它是如何工作的:)。