【发布时间】:2016-08-07 16:05:22
【问题描述】:
我有一个包含两个部分的表格视图和一个在选择单元格时显示的自定义复选标记。
唯一的问题是,如果我选择一个单元格并向下滚动,则每次该单元格出现在屏幕上时都会重新选择该单元格,而所有其他单元格都会再次隐藏。
那么我怎样才能让一个单元格只被选中/取消选中一次。
我的代码:
//Keep track of selected row
var selectedRow: NSIndexPath? = NSIndexPath(forRow: 0, inSection: 0)
func loadStates() {
ApiService.getStates() { (JSON) -> () in
self.states = JSON["stateData"]
self.tableView.reloadData()
let index = NSIndexPath(forRow: 0, inSection: 0)
self.tableView.selectRowAtIndexPath(index, animated: true, scrollPosition: UITableViewScrollPosition.Top)
}
}
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
loadStates()
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let paths:[NSIndexPath]
if let previous = selectedRow {
paths = [indexPath, previous]
} else {
paths = [indexPath]
}
selectedRow = indexPath
tableView.reloadRowsAtIndexPaths(paths, withRowAnimation: .None)
if (indexPath.section == 1) {
tableView.deselectRowAtIndexPath(indexPath, animated: false)
performSegueWithIdentifier("searchCitySegue", sender: indexPath)
}else {
tableView.deselectRowAtIndexPath(indexPath, animated: false)
dismissViewControllerAnimated(true, completion: nil)
}
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 2
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if (section == 1){
return states.count
}
return 1
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell: searchStateTableViewCell!
if (indexPath.section == 0) {
cell = tableView.dequeueReusableCellWithIdentifier("staticStateCell") as! searchStateTableViewCell
cell.titleLabel?.text = "All states"
if indexPath == selectedRow {
cell.stateImage.select()
} else {
cell.stateImage.deselect()
}
}else if (indexPath.section == 1) {
cell = tableView.dequeueReusableCellWithIdentifier("stateCell") as! searchStateTableViewCell
let state = states[indexPath.row]
cell.configureWithStates(state)
if indexPath == selectedRow {
cell.stateImage.select()
} else {
cell.stateImage.deselect()
}
}
return cell
}
那么,是什么导致我的单元格在每次重新出现在屏幕上时运行选定的动画?
【问题讨论】:
标签: ios swift uitableview tableview