ios - Swift 导航栏搜索栏在单击时忽略搜索文本

标签 ios iphone swift xcode searchbar

当我在搜索栏中搜索时,它会相应地给出结果,但是当我单击外部以选择我的选项时,搜索栏占位符将变为零,并且只有搜索到的选项可用。要获取所有选项,我必须再次打开搜索栏并按取消,这将重新加载表格 View 以显示所有选项。

Home Screen
Entering text in search bar
After clicked on the screen

import UIKit

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

let locationNames = ["Python", "C#", "Machine Learning"]

let locationImages = [UIImage(named: "hawaiiResort"), UIImage(named: "mountainExpedition"), UIImage(named: "scubaDiving")]

let locationDescription = ["Beautiful resort off the coast of Hawaii", "Exhilarating mountainous expedition through Yosemite National Park", "Awesome Scuba Diving adventure in the Gulf of Mexico"]

let searchController = UISearchController(searchResultsController: nil)
@IBOutlet weak var collectionView: UICollectionView!
var searchResult = [String]()
var searching = false
override func viewDidLoad() {
    navigationItem.title = "Courses"
    navigationController?.navigationBar.prefersLargeTitles = true
    self.navigationItem.largeTitleDisplayMode = .always

    searchController.searchResultsUpdater = self
    searchController.searchBar.delegate = self
    navigationItem.searchController = searchController
    definesPresentationContext = true
    currentPage = 0
}


func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    if(searching){
    return searchResult.count
    }
    else{
    return 3
    }


}

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

    if(searching)
    {
        cell.locationName.text = searchResult[indexPath.row]
        let people = locationNames.index{$0 == String(searchResult[indexPath.row])}
        cell.locationImage.image = locationImages[people ?? 0]
        cell.locationDescription.text = locationDescription[people ?? 0]
    }
    else
    {
    cell.locationImage.image = locationImages[indexPath.row]
    cell.locationName.text = locationNames[indexPath.row]
    cell.locationDescription.text = locationDescription[indexPath.row]
    }


    cell.contentView.layer.cornerRadius = 4.0
    cell.contentView.layer.borderWidth = 1.0
    cell.contentView.layer.borderColor = UIColor.clear.cgColor
    cell.contentView.layer.masksToBounds = false
    cell.layer.shadowColor = UIColor.gray.cgColor
    cell.layer.shadowOffset = CGSize(width: 0, height: 1.0)
    cell.layer.shadowRadius = 4.0
    cell.layer.shadowOpacity = 1.0
    cell.layer.masksToBounds = false
    cell.layer.shadowPath = UIBezierPath(roundedRect: cell.bounds, cornerRadius: cell.contentView.layer.cornerRadius).cgPath


    return cell
}

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

    let vc = self.storyboard?.instantiateViewController(withIdentifier: "ContentViewController") as! ContentViewController

    vc.selectedCourse = locationNames[indexPath.row]

    self.navigationController?.pushViewController(vc, animated: true)
}
}

extension ViewController: UISearchResultsUpdating{
    func updateSearchResults(for searchController: UISearchController) {
        guard let searchText = searchController.searchBar.text else { return }



    searchResult = locationNames.filter({$0.prefix(searchText.count) == searchText})
    searching = true
    collectionView.reloadData()
}
//    func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
//        searchResult = locationNames.filter({$0.prefix(searchText.count) == searchText})
//        searching = true
//        collectionView.reloadData()
//    }

func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
    NSLog("%@",searchBar.text ?? "");
}
func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
    searching = false
    searchBar.text = ""
    collectionView.reloadData()
}
}

我是 Swift 新手。

最佳答案

首先,您应该让updateSearchResults(for:)使过滤/更新工作正常,这是它的唯一目的。

对于答案,也许您正在设置 isActive UISearchController的方法至false当点击 searchBar 外部时,导致其中的文本被删除,并且不允许搜索 Controller 相应更新以再次重新加载所有数据。

因此,解决方案可能是添加 searchBarTextDidEndEditing(_) searchBar时重置数据源的方法不再是第一响应者:

func searchBarTextDidEndEditing(_ searchBar: UISearchBar) {
    searching = false
    searchResult = locationNames
    collectionView.reloadData()
}

或者更好的是,让updateSearchResults(for:)自动更新数据的方法:

func updateSearchResults(for searchController: UISearchController) {
    guard let searchText = searchController.searchBar.text else { return }

    searchResult = locationNames.filter({$0.prefix(searchText.count) == searchText})
    collectionView.reloadData()
}

关于ios - Swift 导航栏搜索栏在单击时忽略搜索文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54135226/

相关文章:

ios - 如何将 UITextView 的宽度更改为最长文本行的宽度?

ios - 向 coredata 添加一个新实体——我还能使用轻量级迁移吗?

ios - 更改可操作的推送通知按钮颜色和字体

ios - 核心数据 : How do I add additional entities to an existing many-to-many relationship

ios - 如何仅在一个表格 View 单元格中更改标签并使用 Swift 保存?

iOS 支持外接键盘而不显示

ios - 移动浏览器时间输入在 vue 元素内不起作用

iphone - 不使用导航 Controller 的 UISearchController

iphone - iOS OpenGL ES 2.0 : Offscreen render and save the result to an UIImage

Swift:无法将 .prettyPrinted 格式的字符串添加到 forHTTPHeaderField