【发布时间】:2015-04-05 16:55:21
【问题描述】:
我的应用程序的主表视图包含一个带有 UISearchBar 的列表。该应用程序允许用户选择多个列表条目,并通过电子邮件发送。
当用户在搜索栏中选择一个列表条目时,以下代码会存储所选项目的信息:
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
// Code to store description of selected cell
let selectedCell = tableView.cellForRowAtIndexPath(indexPath)
println(selectedCell)
// Code to store indexPath of selected cell
rowToSelect = tableView.indexPathForSelectedRow()
println(rowToSelect)
// Code to store textLabel of selected cell
selectedCellTitle = selectedCell?.textLabel?.text ?? ""
println("The stored cell is called \(selectedCellTitle)")
}
然后,我使用以下代码在主表视图的搜索视图中重新选择选定的单元格:
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = self.tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as UITableViewCell
if tableView == self.searchDisplayController!.searchResultsTableView {
cell.textLabel?.text = filteredPublications[indexPath.row].valueForKey("fullTitle") as? String
cell.detailTextLabel?.text = filteredPublications[indexPath.row].valueForKey("journal") as? String
println(filteredPublications)
} else {
cell.textLabel?.text = publications[indexPath.row].valueForKey("fullTitle") as? String
cell.detailTextLabel?.text = publications[indexPath.row].valueForKey("journal") as? String
self.tableView.selectRowAtIndexPath(rowToSelect, animated: true, scrollPosition: .Top)
}
return cell
}
这不起作用,因为搜索视图中列表条目的 indexPath 不等于主 tableView 中相同条目的 indexPath。从搜索视图返回后,如何在主 tableView 中选择相等的条目?
(一个建议是将textLabel存储在搜索视图中,就像上面代码中的selectedCellTitle一样。然后,我可以遍历主tableView中的所有单元格,找到与变量selectedCellTitle具有相同标题的单元格。然后,我可以存储该单元格的indexPath。然后,我可以重新选择单元格。但是,我不知道如何编写循环遍历所有单元格,并过滤单元格标题等于 selectedCellTitle 的单元格。我的尝试如下,但不起作用。)
for publication in publications {
if let fullTitle = publication.valueForKey("fullTitle") as? NSString {
if fullTitle.containsString(selectedCellTitle) {
var rowToSelectIndexPath = publication.indexPath
self.tableView.selectRowAtIndexPath(rowToSelectIndexPath)
}
}
}
【问题讨论】:
标签: ios uitableview swift didselectrowatindexpath