nerras
nerras

Reputation: 91

Swift - Programmatically set UITableViewCell resets on scroll

So I'm setting a UITableViewCell's layout programmatically when it is selected:

 override func tableView(tableView: UITableView,  didSelectRowAtIndexPath indexPath: NSIndexPath) {
    self.selectedCellIndexPath = indexPath
    var selectedCell = tableView.cellForRowAtIndexPath(indexPath)!
    tableView.beginUpdates()
    tableView.endUpdates()
    var cell:SelectedPatientCell = tableView.dequeueReusableCellWithIdentifier("patient selected", forIndexPath: indexPath) as! SelectedPatientCell
    cell.patientName.text = patients[indexPath.row].fullName
    cell.dob.text = patients[indexPath.row].dob
    ...
    selectedCell = cell
}

And when I scroll the tableView, the layout of the cell resets to its original layout set in cellForRowAtIndexPath. However, the height stays as it should when I set it in the function above. Does anyone know how to fix this?

Here is an album of what's happening: https://i.sstatic.net/Gj1eW.jpg

Image 1:original state

Image 2: selected state (how it should stay on scrolling)

Image 3: what actually happens

Upvotes: 0

Views: 906

Answers (2)

nerras
nerras

Reputation: 91

So I found my own solution: Instead of doing

    tableView.beginUpdates()
    tableView.endUpdates()

I needed to do this at the end of the function:

    tableView.reloadData()

and that solves the issue

Upvotes: 0

xiaoming
xiaoming

Reputation: 130

you should hold this state in

 func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

    if indexPath == self.selectedCellIndexPath {
        var cell:SelectedPatientCell = tableView.dequeueReusableCellWithIdentifier("patient selected", forIndexPath: indexPath) as! SelectedPatientCell
        cell.patientName.text = patients[indexPath.row].fullName  
        cell.dob.text = patients[indexPath.row].dob
        return cell
    }
    let cell = tableView.dequeueReusableCellWithIdentifier("patient selected") as! OriCell
    ...
    return cell
 }

in this way if you scroll tableView,it won't resume to original Cell. Hopefully it is clear.

Upvotes: 1

Related Questions