Diego
Diego

Reputation: 45

TableView with custom cells repeats first and last cell's containing images

Im having trouble when displaying images inside a ScrollView in a custom cell class called ProductHomeCell. The images contained in the last cell's horizontal scrollView are copied in the first cell's when I go scrolling down. Heres the method that fills each custom cell.

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

     let cell = tableView.dequeueReusableCellWithIdentifier("productCell", forIndexPath: indexPath) as! ProductHomeCell

        cell.productName.text = productImages[indexPath.row].name
        cell.productPrice.text = "$"+productImages[indexPath.row].price
        cell.matchLbl.text = "\(productImages[indexPath.row].match)"

        // cell.PageImages contains Array of Images for scrollView
        cell.pageImages = productImages[indexPath.row].imageSet

    return cell

}

Heres some attributes and methods from ProductHomeCell that sets the scrollView with the images sent and the other attributes.

 import Foundation
 import UIKit


 class ProductHomeCell: UITableViewCell, UIScrollViewDelegate {


@IBOutlet weak var scrollView: UIScrollView!

@IBOutlet weak var matchLabel: UILabel!

@IBOutlet weak var matchLbl: UILabel!


@IBOutlet weak var productName: UILabel!

@IBOutlet weak var comprarBtn: UIButton!

@IBOutlet weak var productPrice: UILabel!



var pageViews: [UIImageView?] = []
var pageControl : UIPageControl = UIPageControl(frame: CGRectMake(60, 300, 200, 5))

var pageImages : [UIImage] = [] {

    didSet {

        let pageCount = pageImages.count
        self.pageControl.numberOfPages = pageCount
        configurePageControl()
        pageControl.enabled = false

        // 3
        for _ in 0..<pageCount {
            pageViews.append(nil)
        }

        // 4
        let pagesScrollViewSize = scrollView.frame.size


        scrollView.contentSize = CGSize(width: pagesScrollViewSize.width * CGFloat(pageImages.count),
            height: pagesScrollViewSize.height)

        if pageCount == 1 {

            self.pageControl.hidden = true

        }

        loadVisiblePages()





    }


    }


override func awakeFromNib() {



    super.awakeFromNib()
    scrollView.delegate = self
    pageControl = UIPageControl(frame: CGRectMake(240, 0, 107, 37))
    likeButton.setImage(UIImage(named:"corazon_borde_rojo"),forState:UIControlState.Normal)

    comprarBtn.layer.borderColor = UIColor.lightGrayColor().CGColor
    comprarBtn.layer.borderWidth = 0.5
    comprarBtn.layer.cornerRadius = 12.0
    comprarBtn.clipsToBounds = true

    // 4
    let scrollViewFrame = scrollView.frame
    let scaleWidth = scrollViewFrame.size.width / scrollView.contentSize.width
    let scaleHeight = scrollViewFrame.size.height / scrollView.contentSize.height
    let minScale = min(scaleWidth, scaleHeight);
    scrollView.minimumZoomScale = minScale;

    // 5
    scrollView.maximumZoomScale = 1.0
    scrollView.zoomScale = minScale;




}

func loadPage(page: Int) {
    if page < 0 || page >= pageImages.count {
        // If it's outside the range of what you have to display, then do nothing
        return
    }

    // 1
    if let pageView = pageViews[page] {
        // Do nothing. The view is already loaded.
    } else {
        // 2
        var frame = scrollView.bounds
        frame.origin.x = frame.size.width * CGFloat(page)
        frame.origin.y = 0.0

        // 3
        let newPageView = UIImageView(image: pageImages[page])
        // let newPageView = UIImageView(image: imageC)

        newPageView.contentMode = .ScaleAspectFit
        newPageView.frame = frame

        scrollView.addSubview(newPageView)

        // 4
        pageViews[page] = newPageView
    }
}

func loadVisiblePages() {
    // First, determine which page is currently visible
    let pageWidth = scrollView.frame.size.width
    let page = Int(floor((scrollView.contentOffset.x * 2.0 + pageWidth) / (pageWidth * 2.0)))

    // Work out which pages you want to load
    let firstPage = page - 1
    let lastPage = page + 1

    // Purge anything before the first page
    for var index = 0; index < firstPage; ++index {
        purgePage(index)
    }

    // Load pages in our range
    for index in firstPage...lastPage {
        loadPage(index)
    }

    // Purge anything after the last page
    for var index = lastPage+1; index < pageImages.count; ++index {
        purgePage(index)
    }
}

func scrollViewDidScroll(scrollView: UIScrollView) {
    // Load the pages that are now on screen
    loadVisiblePages()
}

func purgePage(page: Int) {
    if page < 0 || page >= pageImages.count{
        // If it's outside the range of what you have to display, then do         nothing
        return
    }

    // Remove a page from the scroll view and reset the container array
    if let pageView = pageViews[page] {
         pageView.removeFromSuperview()

        pageViews[page] = nil
    }
}

override func setSelected(selected: Bool, animated: Bool) {
    super.setSelected(selected, animated: animated)

    // Configure the view for the selected state
}


func configurePageControl() {

    self.pageControl.currentPage = 0
    self.pageControl.tintColor = UIColor.blackColor()

    self.pageControl.pageIndicatorTintColor = UIColor.lightGrayColor()
    self.pageControl.currentPageIndicatorTintColor = UIColor.blackColor()
    self.addSubview(pageControl)
}

func scrollViewDidEndDecelerating(scrollView: UIScrollView) {
    let pageNumber = round(scrollView.contentOffset.x / scrollView.frame.size.width)
    pageControl.currentPage = Int(pageNumber)
}

@IBOutlet weak var likeButton: UIButton!


@IBAction func darLike(sender: AnyObject) {

    if((likeButton.imageView?.image?.isEqual(UIImage(named: "corazon_borde_rojo"))) != nil){
        likeButton.setImage(UIImage(named:"corazon_rojo"),forState: UIControlState.Normal)



    }

}

@IBAction func verDetail(sender: AnyObject) {



}


override func prepareForReuse() {
    super.prepareForReuse()

    loadVisiblePages()

}





 }

This class also contains methods that set up the scroll view and pageControl horizontally with the correspondent images.

The PROBLEM as I mentioned is that when I scroll down the images from the last cells replace the first cell's images but not the attributes as price or description. ONLY images. Thanks!

Upvotes: 4

Views: 963

Answers (2)

Diego
Diego

Reputation: 45

The problem was that I had to empty the scrollView removing each subView and all of its data in the cellForRowAtIndexPath method.

Upvotes: 0

Sverrisson
Sverrisson

Reputation: 18157

Your cells are reused so make sure to clear all values before a cell is setup.

Upvotes: 1

Related Questions