【发布时间】:2016-03-01 10:08:24
【问题描述】:
我正在尝试实现 UISearchController(不是已弃用的 UISearchDisplayController)
我面临着一个荒谬的吃饭时间问题。
当我尝试dequeueResusableCellWithIdentifier 时,它不适用于我的CellAutocompletion(UITableViewCell 子类化)
像这样:
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let item = filteredProducts[indexPath.row]
let cell:CellAutocompletion = self.tableView.dequeueReusableCellWithIdentifier("suggestionCell") as! CellAutocompletion
cell.itemLabel?.text = item.item_name;
return cell
}
这把我扔了fatal error: unexpectedly found nil while unwrapping an Optional value
但是当我这样做时:
let cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "suggestionCell");
它有效。因此,对于默认 iOS 单元,它可以工作,而我的自定义单元则不行。有什么想法吗?
我想我问错了 tableview,但考虑到我在 UISearchController 中包含的 TableviewController 被另一个 VC 使用,我迷路了。
我的主要 VC 实例化了我的 searchController 和我遇到问题的 TableViewController。
//ViewDidLoad
resultsTableController = ProductResultTabController();
resultsTableController.tableView.delegate = self;
self.searchController = UISearchController(searchResultsController: resultsTableController);
searchController.searchResultsUpdater = self;
searchController.dimsBackgroundDuringPresentation = true;
searchController.searchBar.sizeToFit()
tableView.tableHeaderView = searchController.searchBar
我的 CustomCell 类
class CellAutocompletion:UITableViewCell{
@IBOutlet weak var itemLabel: UILabel!
@IBOutlet weak var parentItemLabel: UILabel!
}
ProductResultTabController(TableViewController 的子类)
class ProductResultTabController: UITableViewController {
var filteredProducts = [ITEM]();
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1;
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return filteredProducts.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let item = filteredProducts[indexPath.row]
let cell:CellAutocompletion = self.tableView.dequeueReusableCellWithIdentifier("suggestionCell") as! CellAutocompletion!
cell.itemLabel?.text = item.item_name;
return cell
}
}
【问题讨论】:
-
您的 resultsTableController 是否存在于代码或情节提要中?如果是前者,您的单元格是否在情节提要中进行了原型设计?如果是后者,您的 tableView 是否调用
registerNib:或registerClass:forCellReuseIdentifier? -
resultController 存在于代码和情节提要中,我已将它与情节提要中的 TableViewController 相关联,并在我的主 VC 中与 searchController
self.searchController = UISearchController(searchResultsController: resultsTableController);和 Cell 进行原型化,并与我的自定义 Cell 相关联类(和 IBoutlet 也链接) -
是的,但是你像这样调用 init
resultsTableController = ProductResultTabController();你能发布ProductResultTabController的代码吗 -
好的,接听来电。
标签: ios swift uitableview custom-cell uisearchcontroller