在TableView上添加SearchBar

时间:2015-10-07 13:56:15

标签: ios swift uitableview core-data uisearchbar

我想在我的tableview中添加一个搜索栏,其中填充了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
}

}

1 个答案:

答案 0 :(得分: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()
}

}