Custom UITableViewCell causing UISearchBar to cras

2019-06-24 18:57发布

I have a tableView with a UISearchBar set up. Every time the user starts typing in the search bar the app crashes. I discovered that the problem is that I'm using a custom tableViewCell (when I tried running the app with the default tableViewCell it didn't crash and worked fine.). Any ideas on how to fix this? Thanks.

Here's my code:

import UIKit
import CoreData


class KeepTableViewController: UITableViewController, UISearchBarDelegate{

    @IBOutlet weak var searchBar: UISearchBar!

    var filteredQuotes = [AnyObject]()
    var keptQuotes = [NSManagedObject]()

    override func viewDidLoad() {
        super.viewDidLoad()

        searchBar.delegate = self
        searchBar.showsScopeBar = true

        tableView.rowHeight = UITableViewAutomaticDimension

        getCoreData()


    searchDisplayController?.searchResultsTableView.registerClass(QuoteyTableViewCell.self, forCellReuseIdentifier: "Cell")

    }


    func getCoreData(){

        var appDel : AppDelegate = UIApplication.sharedApplication().delegate as AppDelegate
        var context : NSManagedObjectContext = appDel.managedObjectContext!
        var req : NSFetchRequest = NSFetchRequest(entityName: "KeptQuotes")

        var error : NSError?

        let fetchedResults = context.executeFetchRequest(req, error: &error) as [NSManagedObject]?

        if let results = fetchedResults {

            keptQuotes = results

        }else{

            println("Could not fetch \(error), \(error!.userInfo)")

        }

        tableView.reloadData()

    }

    @IBAction func cancelPressed(sender: AnyObject) {

        dismissViewControllerAnimated(true, completion: nil) //dismisses the freakin view
    }

    override func preferredStatusBarStyle() -> UIStatusBarStyle {

        return UIStatusBarStyle.LightContent
    }

    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 Potentially incomplete method implementation.
        // Return the number of sections.

    return 1

    }

    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete method implementation.
        // Return the number of rows in the section.

        if tableView == self.searchDisplayController?.searchResultsTableView {

            return filteredQuotes.count

        }else{

            return keptQuotes.count

    }

    }


    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

        let cell : QuoteyTableViewCell = tableView.dequeueReusableCellWithIdentifier("Cell") as QuoteyTableViewCell

        var entry : NSManagedObject

        if tableView == self.searchDisplayController!.searchResultsTableView{

            entry = filteredQuotes[indexPath.row] as NSManagedObject

        }else{

            entry = keptQuotes[indexPath.row] as NSManagedObject!

        }

        cell.authorLabel.text = entry.valueForKey("author") as String!
        cell.quoteTextLabel.text = entry.valueForKey("quote") as String!

        cell.quoteTextLabel.sizeToFit()
        cell.selectionStyle = UITableViewCellSelectionStyle.None

        return cell
    }



    func filterContentForSearchText(searchText: String) {

        var qs : NSArray = keptQuotes

        let predicate = NSPredicate(format: "quote contains[c] %@ OR author contains[c] %@", searchText, searchText)

        filteredQuotes = qs.filteredArrayUsingPredicate(predicate!)
        println(filteredQuotes)


    }

    func searchDisplayController(controller: UISearchDisplayController!, shouldReloadTableForSearchString searchString: String!) -> Bool {

        self.filterContentForSearchText(searchString)
        return true
    }

    func searchDisplayController(controller: UISearchDisplayController!, shouldReloadTableForSearchScope searchOption: Int) -> Bool {

        self.filterContentForSearchText(searchDisplayController!.searchBar.text)
        return true
    }

}

Custom TableViewCell:

import UIKit

class QuoteyTableViewCell: UITableViewCell {

    @IBOutlet weak var authorLabel: UILabel!
    @IBOutlet weak var quoteTextLabel: UILabel!

    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code

        quoteTextLabel.textColor = UIColor(rgba: "#293B50")
        authorLabel.textColor = UIColor(rgba: "#A4ACB5")

    }

    override func setSelected(selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }

}

1条回答
孤傲高冷的网名
2楼-- · 2019-06-24 19:34

I came across the same problem as yours too not too long ago. What I did to make mine work was instead of laying out my custom cell directly in the prototype cell, I created a separate .xib file for it, set the prototype cells in my tableViewController to 0 and did

let regularCell = UINib(nibName: "Cell", bundle: nil)

self.searchDisplayController!.searchResultsTableView.registerNib(regularCell, forCellReuseIdentifier: "Cell")
查看更多
登录 后发表回答