【发布时间】:2016-01-13 10:01:00
【问题描述】:
我正在尝试在搜索视图和非搜索视图之间同步 accessoryType.Checkmark。我尝试在cellForRowAtIndexPath 的几个不同位置设置cell.accessoryType = .None,但是当我在fetchedResults 和搜索结果之间切换时,我不断得到随机复选标记。我不知道我在搞砸什么,但我确信这将是一件非常愚蠢的事情。
我设置了一个UITableViewController。当它加载时,我将它配置为显示来自NSFetchRequest 的项目。效果很好。
我也设置了一个UISearchController。它完美运行并显示我想要的结果。
我在搜索和 fetchRequest 之间切换时遇到随机复选标记的问题。我要保存的一系列东西运行良好,并且正确的项目在那里——它是被选中的复选标记。任何反馈将不胜感激。我没有想法。
这是我在 viewDidLoad 之前在 UITableViewController 类中声明的相关属性:
// Create array to dump fetchResults
var unfilteredJingles = [Jingle]()
// Create array to store filtered search results
var filteredJingles = [Jingle]()
// Array where ones I want to save get added/removed
var jinglesToSave = [Jingle]()
// resultsSearchController
var resultsSearchController = UISearchController()
当单元格被选中时,我将didSelectRowAtIndexPath 配置为做两件事:
1) 将该单元格的jinglesToSave 附加到一个数组并在该单元格旁边放置一个复选标记。这行得通。
2) 从jinglesToSave 数组中删除该单元格的jinglesToSave。这也有效。
我遇到的问题是当我在searchResultsController.active 和searchResultsController 不活动之间切换时检查随机单元格。正确的单元格保持检查状态,但有时会检查随机的单元格。
这是我的cellForRowAtIndexPath:
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("jingleCell", forIndexPath: indexPath)
// instantiate a local array and assign it to filtered/unfiltered results based on whether
// the resultsSearchController is active
var jingleArray = [Jingle]()
if resultsSearchController.active {
// set local array to the filtered array
jingleArray = filteredJingles
let jingle = jingleArray[indexPath.row]
// Set labels for cell
cell.textLabel?.text = jingle.jingleDescription
cell.detailTextLabel?.text = jingle.jingleStar
} else {
// set the local array to the UN-filtered array
jingleArray = unfilteredJingles
// Get the jingle for the index
let jingle = jingleArray[indexPath.row]
// Set labels for cell
cell.textLabel?.text = jingle.jingleDescription
cell.detailTextLabel?.text = jingle.jingleStar
}
// Set checkmarks
if self.jinglesToSave.count > 0 {
// enumerate jinglesToSave...
for (indexOfJinglesToSave, jingleToSave) in jinglesToSave.enumerate() {
// if the object in the array of stuff to save matches the object in the index of the tableview
if jingleArray[indexPath.row].hashValue == jinglesToSave[indexOfJinglesToSave].hashValue {
// then set its accessoryView to checkmark
cell.accessoryType = .Checkmark
}
}
}
return cell
}
【问题讨论】:
标签: ios swift uitableview core-data uisearchcontroller