如何在搜索栏中单击“输入”按钮后更新视图控制器以显示搜索结果?

时间:2015-11-04 00:16:58

标签: ios swift core-data

现在我有UISearchBar(我不添加UISearchDisplayController)。 现在我需要:当我在UISearchBar中输入一些单词并按回车键时,CategoryListViewController应显示搜索结果。如果我没有在搜索栏中输入任何内容,CategoryListViewController应显示所有数据。 键入单词并单击“输入”按钮后,我可以获取输入的文本。但是如何显示搜索结果? (我使用核心数据来存储数据)。 关于CategoryListViewController

import Foundation
import UIKit
import CoreData
class CategoryListViewController: UIViewController,UITableViewDataSource, UITableViewDelegate,UISearchBarDelegate
{


func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    guard let count = resultController?.sections?.count else
    {
        return 0
    }

    return count
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
     if (searchCategory != nil)
     {
        return 1
     }

        guard let count = resultController?.sections?[section].numberOfObjects
        else
        {
            return 0
        }


    return count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
    let cell:UITableViewCell

    cell = tableView.dequeueReusableCellWithIdentifier("firstrow", forIndexPath: indexPath)

    if let category = resultController?.objectAtIndexPath(indexPath) as? Category, let title = category.title,let images = category.image
    {

        cell.textLabel?.text = title


        let number = images.count

      cell.detailTextLabel?.text = "Contains \(number) images"

    }

    return cell
}
@IBOutlet weak var tableView: UITableView!


@IBOutlet weak var searchView: UISearchBar!

func searchBarCancelButtonClicked(searchBar: UISearchBar)
{
    self.view.endEditing(true)
}



override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?)
{
    switch segue.identifier {
    case .Some("catSegue"):
        let indexPath = tableView.indexPathForSelectedRow!
        let viewController = segue.destinationViewController as! CatImagesViewController
        viewController.navigationItem.title = "Cat Images"

        tableView.deselectRowAtIndexPath(indexPath, animated: false)

        if let category = resultController?.objectAtIndexPath(indexPath) as? Category, /*let title = category.title,*/ let images = category.image
        {

            viewController.target_category = category
            viewController.number_of_cells = images.count

        }


    default:
        super.prepareForSegue(segue, sender: sender)
    }
}
// MARK: View Life Cycle
override func viewDidLoad() {
    super.viewDidLoad()
    tableView.delegate = self
    tableView.dataSource = self
    searchView.delegate = self

    //--------------------------------
    if (searchCategory != nil)
    {
        resultController = try? CatService.sharedCatService.catCategories(searchCategory)
    }
    else
    {
        resultController = try? CatService.sharedCatService.catCategories()

    }


}

func searchBarSearchButtonClicked(searchBar: UISearchBar) {
   // print("searchText2 \(searchBar.text)")

    searchCategory = searchBar.text
    self.viewDidLoad()
}

private var searchCategory:String?
private var resultController: NSFetchedResultsController?
private var imageController: NSFetchedResultsController?
}

关于获取搜索结果的核心数据部分:

    func catCategories(searchTerm: String? = nil) throws -> NSFetchedResultsController {
let fetchRequest = NSFetchRequest(entityName: "Category")

//let fetchRequest = NSFetchRequest(namedEntity: Image.self)

if let someSearchTerm = searchTerm
{
    fetchRequest.predicate = NSPredicate(format: "title == %@", someSearchTerm )
    print("somesearchTerm is \(someSearchTerm)")
}



fetchRequest.sortDescriptors = [NSSortDescriptor(key:"title",ascending: true)]

let mainQueueContext = CoreDataService.sharedCoreDataService.mainQueueContext
let fetchResultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: mainQueueContext, sectionNameKeyPath: nil, cacheName: nil)

try fetchResultsController.performFetch()
return fetchResultsController

}

1 个答案:

答案 0 :(得分:1)

我也想过滤“就地”,即不使用搜索控制器和搜索结果的叠加层。我通常遵循这种模式。

如果搜索字词为nil或没有内容,则应明确将获取结果控制器的获取请求的谓词设置为nil

fetchRequest.predicate = (someSearchTerm ?? "").characters.count == 0 ? nil :
     NSPredicate(format:"title BEGINSWITH %@", someSearchTerm!)

其次,您需要实现此UISearchBarDelegate方法

func searchBarSearchButtonClicked(searchBar: UISearchBar) {
    searchBar.resignFirstResponder()
    someSearchTerm = searchBar.text 
    fetchedResultsController.performFetch()
    tableView.reloadData()
}