定义UITableViewCell导致UISearchBar崩溃

定义UITableViewCell导致UISearchBar崩溃

本文介绍了自定义UITableViewCell导致UISearchBar崩溃的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有UISearchBar的tableView.每次用户开始在搜索栏中输入内容时,应用都会崩溃.我发现问题是我使用的是自定义tableViewCell(当我尝试使用默认tableViewCell运行应用程序时,它没有崩溃并且工作正常.)有想法该怎么解决这个吗?谢谢.

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.

这是我的代码:

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
    }

}

自定义TableViewCell:

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
    }

}

推荐答案

不久前,我遇到了与您相同的问题.我要做的工作不是将自定义单元直接放置在原型单元中,而是为其创建了一个单独的 .xib 文件,然后在我的 tableViewController 中设置了原型单元.code>设为0并完成

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")

这篇关于自定义UITableViewCell导致UISearchBar崩溃的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 17:26