0

tableView 不显示包含我搜索结果的单元格。搜索工作正常,我验证了所有数据,但是当我将 cell.localName?.text 分配给该值时,它总是为零。不知道出了什么问题。我在Objective-C中找到了另一个具有相同问题的帖子,答案是我需要使用真实tableView中的单元格,方法是在使单元格出列时添加self.tableView,但这对我不起作用。有什么建议么?

这是我的代码:

class SearchResultsController: UITableViewController, UISearchResultsUpdating {
var localNames: [String] = []
var filteredNames: [String] = []

override func viewDidLoad() {
    super.viewDidLoad()

    tableView.registerClass(localCell.self, forCellReuseIdentifier: "localCell")
}

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

func updateSearchResultsForSearchController(searchController: UISearchController) {
    let searchedString = searchController.searchBar.text
    filteredNames.removeAll(keepCapacity: true)
    if !searchedString.isEmpty {
        let filter: String -> Bool = {name in
            let range = name.rangeOfString(searchedString, options: NSStringCompareOptions.CaseInsensitiveSearch)
            return range != nil
        }
            let matches = localNames.filter(filter)
            filteredNames += matches

    }
    tableView.reloadData()
}



// MARK: - Table view data source

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


override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell: localCell = self.tableView.dequeueReusableCellWithIdentifier("localCell") as localCell
    cell.localName?.text =  filteredNames[indexPath.row]
    println(cell.localName?.text)
    cell.localAddress?.text = "text"
    cell.scheduleData?.text = "text"
    cell.salaData?.text = "text"
    cell.wifiData?.text = "text"
    return cell
}
4

2 回答 2

1

如果您的手机正在返回,请在通话nil后使用以下内容自己创建一个dequeueReusableCellWithIdentifier

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

此外,如果您使用的是 UISearchController,您应该使用 2 个不同的数组来填充您的 UITableView,而不是操作同一个数组。

您可以通过检查搜索控制器在您的 tableView 委托方法中是否处于活动状态并采取相应措施来做到这一点。

于 2015-04-08T23:32:20.317 回答
1

好的,所以我找到了解决方案并发布,以防其他人遇到与我相同的问题。我正在使用来自故事板原型单元的自定义单元。resultController 创建一个新的 tableView,它对自定义单元格一无所知,这就是它总是返回 nil 的原因。为了解决这个问题,我引用了第一次使用的 tableView 而不是新的,或者从真实表格中获取单元格,这样我的自定义单元格就被识别了。

于 2015-04-09T20:33:03.680 回答