I have a tableview with a two sections and a custom checkmark that gets shown when selecting a cell.
The only problem is if I select a cell and scroll down the cell gets re-selected each time the cell shows up on the screen, and all other cells gets hidden again.
So how I can I make that a cell only gets selected/deselected once.
my code:
//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
}
So what is causing my cell to run the selected animation once it reapears on the screen each time?
I'm pretty sure it's because cellForRowAtIndexPath
with this code:
if indexPath == selectedRow {
cell.stateImage.select()
}
else {
cell.stateImage.deselect()
}
is called each time the cell appears. Try:
if indexPath == selectedRow {
if !(cell.selected) {
cell.stateImage.select()
}
}
else {
cell.stateImage.deselect()
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.