nerras nerras - 7 months ago 51
Swift Question

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?

Answer

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.

Comments