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

时间:2016-11-02 22:26:34

标签: ios swift uicollectionview uisearchbar

我应该如何解决这个问题?我不知道如何正确地将Search Bar与UICollectionView集成。请帮我理解这个问题。

P.S。我的语言是Swift

My view in Interface Builder [1]

My view when I run project [2]

import UIKit

class 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
}

}

2 个答案:

答案 0 :(得分:3)

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

    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") 
}


    }

让我知道它的工作原理:)。

答案 1 :(得分:2)

您需要从 Attribute Inspector 中启用 Section header 。见所附图片。也许可以解决您的问题。see image, click on your uicollection view and mark the Section Header