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

标签 ios swift uicollectionview uisearchbar

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

附言我的语言是 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
}

最佳答案

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

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


    }

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

关于ios - 当我运行我的项目时,搜索栏不会出现在 UICollectionView 的标题中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40390863/

相关文章:

ios - UISegmentedControl 中的文本不完全居中?

ios - react-native 中的模态底部菜单

swift - Swift 3 中的对齐内存

ios - CollectionView Flowlayout自定义

ios - OneSignal (iOS) - 未调用 didReceiveNotificationRequest

ios - 如何手动将第三方 Swift 框架导入 Swift iOS 项目?

ios - 向 SKScene 添加点(如 UIPageViewController 中的点)

ios6 - UICollectionView:UICollectionViewCell 对象在 sizeForItemAtIndexPath 中始终为空

ios - UICollectionView 单元格布局超出了 Collection View 的边界

iphone - 归档有关符号链接(symbolic link)的 iOS 项目时出错