Robert Boerema Robert Boerema - 6 months ago 26
Swift Question

UITableViewCell gets new labels on scroll

Maybe this image will better explain the problem I have right now,
enter image description here

And this is the code I have right now.

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

let cell = tableView.dequeueReusableCellWithIdentifier("cell") as UITableViewCell!

let songAlbumImage = UIImageView()
let songSongName = UILabel()

songSongName.text = "\(indexPath.row + 1): \(self.songNames[indexPath.row])"
songSongName.frame = CGRectMake(80, 0, screenWidth-80, 75)
songSongName.font = UIFont(name: "ElliotSans-Regular", size: 18)
songSongName.textColor = UIColor.whiteColor()
songSongName.numberOfLines = 2

let url = NSURL(string: String(songAlbumCovers[indexPath.row]))
let data = NSData(contentsOfURL: url!)

if (data != nil) {
songAlbumImage.hnk_setImageFromURL(url!, placeholder: UIImage(named: "placeholder1.png"), format: Format<UIImage>(name: "image"), failure: { (error) -> () in }) { (image) -> () in
songAlbumImage.image = image
}
} else {
songAlbumImage.image = UIImage(named: "placeholder1.png")
}

songAlbumImage.frame = CGRectMake(0, 0, 75, 75)


cell.addSubview(songAlbumImage)
cell.addSubview(songSongName)

return cell


}


I just want the label to show up once

Answer

I suggest to use UITableviewCell instead of doing add UIImageView and UILabel in CellForRowIndexPath method. But as par your code try to add following two for loop for remove UILabel and UIImageView before add it subview to Cell:

For UILabel:

   for view in cell.subviews  {
        if let label = view as? UILabel {
            label.removeFromSuperview()
        }
    }

For UIImageView:

 for view in cell.subviews  {
        if let imgView = view as? UIImageView {
            imgView.removeFromSuperview()
        }
    }
Comments