beginner_T
beginner_T

Reputation: 427

Changes made in one tableviewcell effect other cells

My problem is, that I have a tableview with a number of cells. Inside of those cells there are images, that get a green border if they are being taped. If I have a lot of cells and I tap for example the first pic in the first cell, that's when the problem happens. When I start scrolling down the table a little faster, other cells of the same type also have the first picture with green border, even though they are in cell number 13 or something. I think that's because they are reusable cells, but how can I make sure, that only the one cell that is being taped, keeps the change? Hope you guys got what I meant, I know it's kinda confusing. Here is one of the two custom cells, with the code that turns the border green. The images of type bouncingRoundImages, are just UIImages, I created the custom subclass of UIImage to make them bounce.

class TwoPicsTableViewCell: UITableViewCell {

@IBOutlet var containerView: UIView!
@IBOutlet var firstImage: bouncingRoundImageView!
@IBOutlet var secondImage: bouncingRoundImageView!

override func awakeFromNib() {
    super.awakeFromNib()
    // Initialization code
    containerView.layer.cornerRadius = 10
    containerView.clipsToBounds = true

    setupFirstImage()
    setupSecondImage()
}


func setupFirstImage() {

    let tappedOne = UITapGestureRecognizer(target: self, action: #selector(checkPicTwo))
    firstImage.addGestureRecognizer(tappedOne)
}

func setupSecondImage() {
    let tappedTwo = UITapGestureRecognizer(target: self, action: #selector(checkPicOne))
    secondImage.addGestureRecognizer(tappedTwo)
}

func checkPicTwo() {

    firstImage.bouncing()

    if secondImage.layer.borderWidth != 0 {
        secondImage.layer.borderWidth = 0
    }
}

func checkPicOne() {

    secondImage.bouncing()

    if firstImage.layer.borderWidth != 0 {
        firstImage.layer.borderWidth = 0
    }
}


}

Upvotes: 2

Views: 289

Answers (1)

Morten Stulen
Morten Stulen

Reputation: 1333

It sounds like a reusable cell problem. Try setting the image to nil and borderWidth to 0 in prepareForReuse.

override func prepareForReuse()
{
    super.prepareForReuse()
    firstImage.image = nil
    secondImage.image = nil
    firstImage.layer.borderWidth = 0
    secondImage.layer.borderWidth = 0
}

Upvotes: 3

Related Questions