Stop the reuse of custom cells Swift
Asked Answered
C

1

8

I have an uitableview with a custom cell which gets data from the array. Custom cell has an uilabel and an uibutton (which is not visible until the uilabel text or the array object which loads for the text - is nil).

On launch everything is fine. When i press the uibutton the array is being appended, the new cells are being inserted below the cell.

But when i scroll - all of a sudden the uibutton appears on other cells where this conditional uilabel text isEmpty is not implied.

Here is how the whole process looks like enter image description here

Here is my code for cellForRowAtIndexPath

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

    var cell:TblCell = self.tableView.dequeueReusableCellWithIdentifier("cell") as! TblCell
    cell.lblCarName.text = someTagsArray[indexPath.row]

    if let text = cell.lblCarName.text where text.isEmpty {
        cell.act1.hidden = false
    } else {
        println("Failed")
    }

    cell.act1.setTitle(answersdict[answersdict.endIndex - 2], forState:UIControlState.Normal)
    cell.act2.setTitle(answersdict.last, forState:UIControlState.Normal)

    return cell
}

So my general question is how do i stop the reuse of those custom cells? As far as i'm aware there is no direct way of doing this on reusablecellswithidentifier in swift, but maybe there are some workarounds on that issue?

Cusp answered 31/8, 2015 at 10:43 Comment(5)
This is nothing to do with the fact that it is reusing cells and everything to do with the fact that you haven't written it properly.Fan
Can you tell what are you trying to achieve, seems like reusing the cells is not blocking you.Filberte
@Fan thank you for the review and feedback. how would you change the code?Cusp
@DavidRobertson inside TblCell add the method prepareForReuse. This is called every time the cell is reused. In this method hide anything that is hidden by default. Set labels to be blank etc...Fan
@Fan thank you! sounds like a good solution)Cusp
G
21

When a cell is reused, it still has the old values from its previous use.

You have to prepare it for reuse by resetting that flag which showed your hidden control.

You can do this either in tableView:cellForRowAtIndexPath: or the cell's prepareForReuse method.

Update:

Here's an example you can add for TblCell:

override func prepareForReuse()
{
    super.prepareForReuse()
    // Reset the cell for new row's data
    self.act1.hidden = true
}
Gwynethgwynne answered 31/8, 2015 at 11:4 Comment(1)
@ShrikantTanwade This code should go into your custom cell file. In above example it is TblCell.Phalanger

© 2022 - 2024 — McMap. All rights reserved.