在 TableView 上添加 SearchBar

Posted

技术标签:

【中文标题】在 TableView 上添加 SearchBar【英文标题】:Adding a SearchBar on TableView 【发布时间】:2015-10-07 13:56:15 【问题描述】:

我想在我的表格视图中添加一个搜索栏,其中填充了来自 Core Data 的数据。下面是我的 TableViewController 中的部分代码。将搜索栏功能放置在 tableview 上后如何开始实现搜索栏功能?

let managedObjectContext =
(UIApplication.sharedApplication().delegate
as! AppDelegate).managedObjectContext

var fetchedLastName = [String]()
var fetchedFirstName = [String]()
var fetchedImage = [UIImage]()

override func viewDidLoad() 
super.viewDidLoad()

NSNotificationCenter.defaultCenter().addObserver(self, selector: "reloadData:",name:"load", object: nil)

let entityDescription =
NSEntityDescription.entityForName("Faculty",
    inManagedObjectContext: managedObjectContext)

let request = NSFetchRequest()
request.entity = entityDescription

do
    let objects = try managedObjectContext.executeFetchRequest(request)

    let results = objects

    if results.count > 0 
        for var i = 0; i < results.count; i += 1
            let match = results[i] as! NSManagedObject

            fetchedLastName.append((match.valueForKey("lastname") as? String)!)
            fetchedFirstName.append((match.valueForKey("firstname") as? String)!)
            let image = match.valueForKey("image") as! NSData
            fetchedImage.append(UIImage(data: image)!)

        
     else 

    

catch



func reloadData(notification: NSNotification)
fetchedLastName.removeAll()
fetchedFirstName.removeAll()
fetchedImage.removeAll()

let entityDescription =
NSEntityDescription.entityForName("Faculty",
    inManagedObjectContext: managedObjectContext)

let request = NSFetchRequest()
request.entity = entityDescription

do
    let objects = try managedObjectContext.executeFetchRequest(request)

    let results = objects

    if results.count > 0 
        for var i = 0; i < results.count; i += 1
            let match = results[i] as! NSManagedObject

            fetchedLastName.append((match.valueForKey("lastname") as? String)!)
            fetchedFirstName.append((match.valueForKey("firstname") as? String)!)
            let image = match.valueForKey("image") as! NSData
            fetchedImage.append(UIImage(data: image)!)

        
     else 

    

catch

self.tableView.reloadData()


override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell 
let cell = tableView.dequeueReusableCellWithIdentifier("TEACH", forIndexPath: indexPath) as! TEACHTableViewCell

let row = indexPath.row

print(fetchedFirstName)

cell.facultyName.text = fetchedLastName[row] + ", " + fetchedFirstName[row]
cell.facultyImage.image = fetchedImage[row]

return cell



【问题讨论】:

您究竟希望搜索栏寻找什么?名字还是姓氏? 你有没有尝试过?如果没有并寻求帮助,请查看此raywenderlich.com/76519/add-table-view-search-swift 名和姓。我要检查链接谢谢:) 【参考方案1】:

试试这段代码,所有测试:

//
//  TEACHTableViewController.swift
//  TEACH
//
//  Created by ICST340.N1 on 9/29/15.
//  Copyright © 2015 IyoTugs. All rights reserved.
//

import UIKit
import CoreData

class TEACHTableViewController: UITableViewController, UISearchBarDelegate,      UISearchControllerDelegate, UISearchResultsUpdating 

var searchController = UISearchController()

var filteredTableData = [[String: AnyObject?]]()
var tableData = [[String: AnyObject?]]()

let managedObjectContext =
(UIApplication.sharedApplication().delegate
    as! AppDelegate).managedObjectContext

var fetchedLastName = [String]()
var fetchedFirstName = [String]()
var fetchedImage = [UIImage]()

override func viewDidLoad() 
    super.viewDidLoad()

    //setup search controller

    searchController = UISearchController(searchResultsController: nil)
    searchController.searchResultsUpdater = self
    searchController.dimsBackgroundDuringPresentation = false
    searchController.delegate = self

    tableView.tableHeaderView = searchController.searchBar
    definesPresentationContext = true
    searchController.searchBar.sizeToFit()

    NSNotificationCenter.defaultCenter().addObserver(self, selector: "reloadData:",name:"load", object: nil)

    let entityDescription =
    NSEntityDescription.entityForName("Faculty",
        inManagedObjectContext: managedObjectContext)

    let request = NSFetchRequest()
    request.entity = entityDescription

    do
        let objects = try managedObjectContext.executeFetchRequest(request)

        let results = objects

        if results.count > 0 
            for var i = 0; i < results.count; i += 1
                let match = results[i] as! NSManagedObject

                fetchedLastName.append((match.valueForKey("lastname") as? String)!)
                fetchedFirstName.append((match.valueForKey("firstname") as? String)!)
                //added this is convert the image
                let image = match.valueForKey("image") as! NSData
                let realImage = UIImage(data: image)!
                fetchedImage.append(UIImage(data: image)!)
                tableData.append(["firstName" : match.valueForKey("firstname"), "lastName" : match.valueForKey("firstname"), "image" : realImage])

            
         else 

        
    
    catch
    // Uncomment the following line to preserve selection between presentations
    // self.clearsSelectionOnViewWillAppear = false

    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
   //        self.navigationItem.rightBarButtonItem = self.editButtonItem()


func reloadData(notification: NSNotification)
    fetchedLastName.removeAll()
    fetchedFirstName.removeAll()
    //Added this to remove all images
    fetchedImage.removeAll()
    tableData.removeAll()

    let entityDescription =
    NSEntityDescription.entityForName("Faculty",
        inManagedObjectContext: managedObjectContext)

    let request = NSFetchRequest()
    request.entity = entityDescription

    do
        let objects = try managedObjectContext.executeFetchRequest(request)

        let results = objects

        if results.count > 0 
            for var i = 0; i < results.count; i += 1
                let match = results[i] as! NSManagedObject

                fetchedLastName.append((match.valueForKey("lastname") as? String)!)
                fetchedFirstName.append((match.valueForKey("firstname") as? String)!)
                //added this is convert the image
                let image = match.valueForKey("image") as! NSData
                let realImage = UIImage(data: image)!
                fetchedImage.append(UIImage(data: image)!)
                tableData.append(["firstName" : match.valueForKey("firstname"), "lastName" : match.valueForKey("firstname"), "image" : realImage])

            
         else 

        
    
    catch

    self.tableView.reloadData()



override func didReceiveMemoryWarning() 
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.


// MARK: - Table view data source

override func numberOfSectionsInTableView(tableView: UITableView) -> Int 
    // #warning Incomplete implementation, return the number of sections
    return 1


override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int 
    // #warning Incomplete implementation, return the number of rows
    if searchController.active 
        return filteredTableData.count
     else 
    return fetchedLastName.count
    



override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell 
    let cell = tableView.dequeueReusableCellWithIdentifier("TEACH", forIndexPath: indexPath) as! TEACHTableViewCell
    if searchController.active 
        let row = indexPath.row

        print(fetchedFirstName)

        let firstName = filteredTableData[row]["firstName"] as! String
        let lastName = filteredTableData[row]["lastName"] as! String
        let image = filteredTableData[row]["image"] as! UIImage

        cell.facultyName.text = lastName + ", " + firstName
        cell.facultyImage.image = image
     else 

    let row = indexPath.row

    print(fetchedFirstName)

    cell.facultyName.text = fetchedLastName[row] + ", " + fetchedFirstName[row]
    cell.facultyImage.image = fetchedImage[row]
    
    return cell


func filterContentForSearchText(searchText: String) 
    for singleTableData in tableData 
        let firstname = singleTableData["firstName"] as! String
        let lastname = singleTableData["lastName"] as! String
        let image = singleTableData["image"] as! UIImage
        print(firstname)
        print(lastname)
        if searchText != "" 
        if (firstname.rangeOfString(searchText) != nil) 
            filteredTableData.append(["firstName" : firstname, "lastName" : lastname, "image" : image])
         else if (lastname.rangeOfString(searchText) != nil) 
            filteredTableData.append(["firstName" : firstname, "lastName" : lastname, "image" : image])
        
         else 
            filteredTableData.append(["firstName" : firstname, "lastName" : lastname, "image" : image])
        
    


func updateSearchResultsForSearchController(searchController: UISearchController) 
    filteredTableData.removeAll()
    filterContentForSearchText(searchController.searchBar.text!)
    tableView.reloadData()

【讨论】:

明天我将在 Mac 前对其进行测试:P 这适用于我的 tableviewcontroller 吗?我应该只编辑我附加到 tableData 的部分吗? 我得到一个 'searchDisplayController' 在 ios 8.0 中已被弃用' 在实现你的代码后我的应用程序关闭了:o 你能给我你的项目的网址,我会修复它 这里是drive.google.com/open?id=0B5-_n15qdwJpcjJlc2hWeURLWlE我这里还没有实现搜索功能,因为我无法让它工作

以上是关于在 TableView 上添加 SearchBar的主要内容,如果未能解决你的问题,请参考以下文章

TableView 的 SearchBar 不起作用

如何在带有部分的 TableView 上创建 SearchBar?

问:带有 JSON 文件的 SearchBar Tableview

如何让 TableView 中的 SearchBar 看起来像设置应用程序中的那样

在搜索栏上方添加空间

在 tableview 中更改 searchBar 的宽度