searchDisplayController, UITableView, Core Data and Swift

旧巷老猫 提交于 2019-12-29 08:08:57

问题


Trying to search in the table with searchDisplayController. Data filtering configured, the search dialog works. Now I want to work with a method prepareForSegue for send current value indexPath to a new UIViewController:

import UIKit
import CoreData

class MainTableViewController: UITableViewController {

var results:AddrBook[]=[]
var searchResults:AddrBook[]=[]

init(style: UITableViewStyle) {
    super.init(style: style)
}

init(coder aDecoder: NSCoder!) {
    super.init(coder: aDecoder)
}

override func viewDidLoad() {
    super.viewDidLoad()

}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
}

override func viewDidAppear(animated: Bool) {
    let request = NSFetchRequest(entityName: "Person")
    request.returnsObjectsAsFaults = false
    let appDelegate:AppDelegate = (UIApplication.sharedApplication().delegate as AppDelegate)
    let context:NSManagedObjectContext = appDelegate.managedObjectContext
    results  = context.executeFetchRequest(request, error: nil) as AddrBook[]
    self.tableView.reloadData()
}

override func numberOfSectionsInTableView(tableView: UITableView?) -> Int {
    return 1
}

override func tableView(tableView: UITableView!, numberOfRowsInSection section: Int) -> Int {
    if tableView == self.searchDisplayController.searchResultsTableView {
        return searchResults.count
    } else {
        return results.count
    }
}

override func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell! {
    var cell = tableView.dequeueReusableCellWithIdentifier("Cell") as? UITableViewCell

    if !cell {
        cell = UITableViewCell(style: UITableViewCellStyle.Value1, reuseIdentifier: "Cell")
    }

    if tableView == self.searchDisplayController.searchResultsTableView {
        cell!.textLabel.text = searchResults[indexPath.row].lastname + " " + searchResults[indexPath.row].firstname
        cell!.detailTextLabel.text = searchResults[indexPath.row].phonenumber
    } else {
        cell!.textLabel.text = results[indexPath.row].lastname + " " + results[indexPath.row].firstname
        cell!.detailTextLabel.text = results[indexPath.row].phonenumber
    }



    return cell
}

override func tableView(tableView: UITableView!, didSelectRowAtIndexPath indexPath: NSIndexPath!) {
    if tableView == self.searchDisplayController.searchResultsTableView {
        self.performSegueWithIdentifier("editPerson", sender : self)
    }
}

override func prepareForSegue(segue: UIStoryboardSegue!, sender: AnyObject?) {

    var indexPath = NSIndexPath()
    if self.tableView == self.searchDisplayController.searchResultsTableView {
        NSLog("Trying recieve indexPath from Search")
        indexPath = self.searchDisplayController.searchResultsTableView.indexPathForSelectedRow()
        NSLog("indexPath from Search")
    }
    else {
        indexPath = self.tableView.indexPathForSelectedRow()
        NSLog("IndexPath from main table")
    }

    let destViewController:DetailViewController! = segue.destinationViewController as DetailViewController

    if segue.identifier == "editPerson" {
        destViewController.receivedPerson = results
        destViewController.indexPath = indexPath
        NSLog("Selected person ID: \(results[indexPath.row].idperson)")
    }
}

override func tableView(tableView: UITableView?, canEditRowAtIndexPath indexPath: NSIndexPath?) -> Bool {
    return true
}


override func tableView(tableView: UITableView!, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath!) {

    let request = NSFetchRequest(entityName: "Person")
    request.returnsObjectsAsFaults = false
    let appDelegate:AppDelegate = (UIApplication.sharedApplication().delegate as AppDelegate)
    let context:NSManagedObjectContext = appDelegate.managedObjectContext

    if editingStyle == .Delete {
        context.deleteObject(results[indexPath.row])
        context.save(nil)
    }

    results.removeAtIndex(indexPath.row)
    tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)

}

func filterContentForSearchText (searchText: String) {
    searchResults = results.filter{
        ($0.lastname as NSString).localizedCaseInsensitiveContainsString("\(searchText)")
    }
}

func searchDisplayController(controller: UISearchDisplayController!, shouldReloadTableForSearchString searchString: String!) -> Bool {
    self.filterContentForSearchText (searchString)
    return true
}

}

In the functions prepareForSegue condition self.tableView == self.searchDisplayController.searchResultsTableView is not fulfilled.

Always assigns indexPath = self.tableView.indexPathForSelectedRow() instead indexPath = self.searchDisplayController.searchResultsTableView.indexPathForSelectedRow(). This causes an error in case of selecting a row in the search result.

Link to project on Dropbox: https://www.dropbox.com/s/bqv46nkoa4s3ibg/lesson-12-2-swift%203.zip


回答1:


self.tableView is the main table view, so the condition

if self.tableView == self.searchDisplayController.searchResultsTableView

will never be true. But you can check if the search is active or not:

if self.searchDisplayController.active {
    // index path from search table ... 
} else {
    // index path from main table ...
}


来源:https://stackoverflow.com/questions/24489926/searchdisplaycontroller-uitableview-core-data-and-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!