1

Hello I have UICollectionView when scrolled disappears label.text and colors are mixed .

My codes here

CustomCollectionViewCell

import UIKit

@IBDesignable
class CustomCollectionViewCell: UICollectionViewCell {

    @IBOutlet weak var label: UILabel!

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        setup()
    }

    override init(frame: CGRect) {
        super.init(frame: frame)
        setup()
    }

    func setup() {
        self.layer.borderWidth = 1.0
        self.layer.borderColor = UIColor.blackColor().CGColor
        self.layer.cornerRadius = 5.0
    }
}

CustomCollectionViewLayout

import UIKit


public var CELL_HEIGHT = 22.0
public var CELL_WIDTH = 40.0


class CustomCollectionViewLayout: UICollectionViewLayout {

    // Used for calculating each cells CGRect on screen.
    // CGRect will define the Origin and Size of the cell.

    let STATUS_BAR = UIApplication.sharedApplication().statusBarFrame.height

    // Dictionary to hold the UICollectionViewLayoutAttributes for
    // each cell. The layout attribtues will define the cell's size 
    // and position (x, y, and z index). I have found this process
    // to be one of the heavier parts of the layout. I recommend
    // holding onto this data after it has been calculated in either 
    // a dictionary or data store of some kind for a smooth performance.
    var cellAttrsDictionary = Dictionary<NSIndexPath, UICollectionViewLayoutAttributes>()

    // Defines the size of the area the user can move around in
    // within the collection view.
    var contentSize = CGSize.zero

    // Used to determine if a data source update has occured.
    // Note: The data source would be responsible for updating
    // this value if an update was performed.
    var dataSourceDidUpdate = true

    override func collectionViewContentSize() -> CGSize {
        return self.contentSize
    }

    override func prepareLayout() {

        // Only update header cells.
        if !dataSourceDidUpdate {

            // Determine current content offsets.
            let xOffset = collectionView!.contentOffset.x
            let yOffset = collectionView!.contentOffset.y

            if collectionView?.numberOfSections() > 0 {
                for section in 0...collectionView!.numberOfSections()-1 {

                    // Confirm the section has items.
                    if collectionView?.numberOfItemsInSection(section) > 0 {

                        // Update all items in the first row.
                        if section == 0 {
                            for item in 0...collectionView!.numberOfItemsInSection(section)-1 {

                                // Build indexPath to get attributes from dictionary.
                                let indexPath = NSIndexPath(forItem: item, inSection: section)

                                // Update y-position to follow user.
                                if let attrs = cellAttrsDictionary[indexPath] {
                                    var frame = attrs.frame

                                    // Also update x-position for corner cell.
                                    if item == 0 {
                                        frame.origin.x = xOffset
                                    }

                                    frame.origin.y = yOffset
                                    attrs.frame = frame
                                }

                            }

                            // For all other sections, we only need to update
                            // the x-position for the fist item.
                        } else {

                            // Build indexPath to get attributes from dictionary.
                            let indexPath = NSIndexPath(forItem: 0, inSection: section)

                            // Update y-position to follow user.
                            if let attrs = cellAttrsDictionary[indexPath] {
                                var frame = attrs.frame
                                frame.origin.x = xOffset
                                attrs.frame = frame
                            }

                        }
                    }
                }
            }


            // Do not run attribute generation code
            // unless data source has been updated.
            return
        }

        // Acknowledge data source change, and disable for next time.
        dataSourceDidUpdate = false

        var maxItemInASection: Int?

        // Cycle through each section of the data source.
        if collectionView?.numberOfSections() > 0 {
            for section in 0...collectionView!.numberOfSections()-1 {

                // Cycle through each item in the section.
                if collectionView?.numberOfItemsInSection(section) > 0 {
                    for item in 0...collectionView!.numberOfItemsInSection(section)-1 {

                        // Build the UICollectionVieLayoutAttributes for the cell.
                        let cellIndex = NSIndexPath(forItem: item, inSection: section)
                        let xPos = Double(item) * CELL_WIDTH
                        let yPos = Double(section) * CELL_HEIGHT

                        let cellAttributes = UICollectionViewLayoutAttributes(forCellWithIndexPath: cellIndex)
                        cellAttributes.frame = CGRect(x: xPos, y: yPos, width: CELL_WIDTH, height: CELL_HEIGHT)

                        // Determine zIndex based on cell type.
                        if section == 0 && item == 0 {
                            cellAttributes.zIndex = 4
                        } else if section == 0 {
                            cellAttributes.zIndex = 3
                        } else if item == 0 {
                            cellAttributes.zIndex = 2
                        } else {
                            cellAttributes.zIndex = 1
                        }

                        // Save the attributes.
                        cellAttrsDictionary[cellIndex] = cellAttributes

                        if maxItemInASection < item {
                            maxItemInASection = item
                        }

                    }
                }

            }
        }

        // Update content size.
        let contentWidth = Double(maxItemInASection ?? 0) * CELL_WIDTH
        let contentHeight = Double(collectionView!.numberOfSections()) * CELL_HEIGHT
        self.contentSize = CGSize(width: contentWidth, height: contentHeight)

    }

    override func layoutAttributesForElementsInRect(rect: CGRect) -> [UICollectionViewLayoutAttributes]? {

        // Create an array to hold all elements found in our current view.
        var attributesInRect = [UICollectionViewLayoutAttributes]()

        // Check each element to see if it should be returned.
        for cellAttributes in cellAttrsDictionary.values.elements {
            if CGRectIntersectsRect(rect, cellAttributes.frame) {
                attributesInRect.append(cellAttributes)
            }
        }

        // Return list of elements.
        return attributesInRect
    }

    override func layoutAttributesForItemAtIndexPath(indexPath: NSIndexPath) -> UICollectionViewLayoutAttributes? {
        return cellAttrsDictionary[indexPath]!
    }

    override func shouldInvalidateLayoutForBoundsChange(newBounds: CGRect) -> Bool {
        return true
    }

}

HttpManager

import Foundation

class HttpManager {

    class func getRequest(url: String, parameter: Dictionary <String, AnyObject>?, completionHandler: (responseData: [Item]?, errorMessage: String?) -> ()) {

        guard let url = NSURL(string: url) else {
            completionHandler(responseData: .None, errorMessage: "URL string was malformed")
            return
        }

        let task = NSURLSession.sharedSession().dataTaskWithURL(url) { (data, response, error) in

            guard error == nil else {
                completionHandler(responseData: .None, errorMessage: error?.localizedDescription)
                return
            }

            guard let data = data else {
                completionHandler(responseData: .None, errorMessage: "Empty Data")
                return
            }

            guard let jsonSerialization =  try? NSJSONSerialization.JSONObjectWithData(data, options:[]), jsonArray = jsonSerialization as? NSArray else {
                completionHandler(responseData: .None, errorMessage: "NSJSONSerialization error")
                return
            }

             var items = [Item]()

            jsonArray.forEach({ (eachItem) -> () in
                guard let dic = eachItem as? NSDictionary else { return }
                guard let service = dic["Seats"] as? String, base = dic["Base"] as? String else {
                    completionHandler(responseData: .None, errorMessage: "JSON structure missmatch")
                    return
                }

                let services = service.componentsSeparatedByString(",")
                let item = Item(base: base, services: services)
                items.append(item)
            })

            completionHandler(responseData: items, errorMessage: .None)
        }

        task.resume()
    }
}

CustomCollectionViewController

class CustomCollectionViewController: UIViewController {

    @IBOutlet weak var collectionView: UICollectionView!


    var items = [Item]()

    override func viewDidLoad() {
        super.viewDidLoad()

        // Uncomment the following line to preserve selection between presentations
        // self.clearsSelectionOnViewWillAppear = false

        getDataFromServer()
    }

    func getDataFromServer() {

        HttpManager.getRequest(url, parameter: .None) { [weak self] (responseData, errorMessage) -> () in

            guard let strongSelf = self else { return }

            guard let responseData = responseData else {
                print("Get request error \(errorMessage)")
                return
            }

            guard let customCollectionViewLayout = strongSelf.collectionView?.collectionViewLayout as? CustomCollectionViewLayout  else { return }

            strongSelf.items = responseData
            customCollectionViewLayout.dataSourceDidUpdate = true

            NSOperationQueue.mainQueue().addOperationWithBlock({ () -> Void in
                strongSelf.collectionView!.reloadData()
            })
        }
    }
}

// MARK: UICollectionViewDataSource
extension CustomCollectionViewController {

     func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        return items.count
    }

    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return items[section].services.count + 1
    }

DID SELECT CODES

  func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        // You must call super to animate selection

        if indexPath.item == 0 {
            print(items[indexPath.section].base)

        } else {

         let clickeditem = items[indexPath.section].services[indexPath.item - 1]



                if let myStringc: String = items[indexPath.section].services[indexPath.item - 1] {
                    var myStringArrc = myStringc.componentsSeparatedByString("*")




                    let satimdurum:Int = Int(myStringArrc[3])!
                    let sirano:Int = Int(myStringArrc[0])!



                    if sirano == 1 || sirano == 2 {

                        if sirano == 2 {



                            if satimdurum == 0 {


                            if koltuksiraid.contains(clickeditem) {

                                if let index = koltuksiraid.indexOf(clickeditem) {
                                    koltuksiraid.removeAtIndex(index)
                                }


                                let selectedCell:UICollectionViewCell = collectionView.cellForItemAtIndexPath(indexPath)!
                                selectedCell.contentView.backgroundColor = UIColor.orangeColor()


                            }else{

                                koltuksiraid.append(clickeditem)

                                let selectedCell:UICollectionViewCell = collectionView.cellForItemAtIndexPath(indexPath)!
                                selectedCell.contentView.backgroundColor = UIColor(red: 62/256, green: 211/256, blue: 238/256, alpha: 1)


                            }

                            }else{


                            }


                        }else{


                            if satimdurum == 0 {



                 if koltuksiraid.contains(clickeditem) {

                        if let index = koltuksiraid.indexOf(clickeditem) {
                            koltuksiraid.removeAtIndex(index)
                        }


                        let selectedCell:UICollectionViewCell = collectionView.cellForItemAtIndexPath(indexPath)!
                            selectedCell.contentView.backgroundColor = UIColor.greenColor()


                    }else{

                        koltuksiraid.append(clickeditem)

                        let selectedCell:UICollectionViewCell = collectionView.cellForItemAtIndexPath(indexPath)!
                        selectedCell.contentView.backgroundColor = UIColor(red: 62/256, green: 211/256, blue: 238/256, alpha: 1)


                    }
                        }else{


                        }


               }
                }

      }
    }
        print(koltuksiraid)



      }

Latest collectionView Codes After @pkc456 s answer.

    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! CustomCollectionViewCell

        cell.label.font.fontWithSize(12)
        cell.label.textColor = UIColor.whiteColor()

        if indexPath.item == 0 {

            cell.label.text = items[indexPath.section].base
            cell.label.frame.size.width = 30
            cell.label.frame.size.height = 30
            cell.label.layer.borderColor = UIColor.clearColor().CGColor
            cell.contentView.backgroundColor = UIColor.clearColor()

        } else {

            if let myStringc: String = items[indexPath.section].services[indexPath.item - 1] {
                var myStringArrc = myStringc.componentsSeparatedByString("*")

                let satimdurum:Int = Int(myStringArrc[3])!
                let sirano:Int = Int(myStringArrc[0])!

                if sirano == 1 || sirano == 2 {

                    cell.label.backgroundColor = (satimdurum == 1) ?  UIColor.redColor() : UIColor.orangeColor()
                    cell.contentView.backgroundColor = (satimdurum == 1) ?  UIColor.redColor() : UIColor.greenColor()
                    cell.label.layer.borderColor = UIColor.blackColor().CGColor
                    cell.alpha = 1

                    if sirano == 2 {
                       cell.frame.size.width = 80
                        cell.layer.frame.size.width = 80
                        CELL_WIDTH = 80.0
                        CELL_HEIGHT = 22.0

                        if satimdurum == 1 {

                            cell.label.alpha = 1
                            cell.label.layer.borderColor = UIColor.redColor().CGColor
                            cell.contentView.backgroundColor = UIColor.redColor()
                            cell.label.text = myStringArrc[1]

                        }else{





                        if myStringArrc[1] == "NULL"  {
                            cell.label.alpha = 0
                            cell.label.layer.borderColor = UIColor.clearColor().CGColor
                            cell.label.frame.size.width = 0
                            cell.label.frame.size.height = 0
                            cell.contentView.backgroundColor = UIColor.clearColor()
                        }else{
                            cell.label.alpha = 1
                            cell.label.backgroundColor = UIColor.orangeColor()//Or put orange color as per your logic based on myStringArrc
                            cell.label.frame.size.width = 40
                            cell.label.frame.size.height = 40
                            cell.contentView.backgroundColor = UIColor.orangeColor()//Or put orange color as per your logic based on myStringArrc
                            cell.label.text = myStringArrc[1]
                        }


                        }

                        cell.label.text = "\(myStringArrc[1])-\(myStringArrc[5])"
                    }else{

                        cell.frame.size.width = 40
                        cell.layer.frame.size.width = 40
                        CELL_HEIGHT = 22.0
                        CELL_WIDTH = 40

                        if satimdurum == 1 {

                            cell.label.alpha = 1
                            cell.label.layer.borderColor = UIColor.redColor().CGColor
                            cell.contentView.backgroundColor = UIColor.redColor()
                            cell.label.text = myStringArrc[1]

                        }else{




                        if myStringArrc[1] == "NULL"  {
                            cell.label.alpha = 0
                            cell.label.backgroundColor = UIColor.clearColor()
                            cell.label.layer.borderColor = UIColor.clearColor().CGColor
                            cell.label.frame.size.width = 0
                            cell.label.frame.size.height = 0
                            cell.contentView.backgroundColor = UIColor.clearColor()
                        }else{
                            cell.label.text = myStringArrc[1]
                            cell.label.alpha = 1
                            cell.label.frame.size.width = 40
                            cell.label.frame.size.height = 40
                            cell.contentView.backgroundColor = UIColor.greenColor()//Or put orange color as per your logic based on myStringArrc
                        }
                             }
                    }
                }else{
                    cell.label.alpha = 0
                    cell.label.layer.borderColor = UIColor.clearColor().CGColor
                    cell.label.frame.size.width = 0
                    cell.label.frame.size.height = 0
                    cell.contentView.backgroundColor = UIColor.clearColor()
                    cell.alpha = 0
                }

            }
        }

        cell.label.backgroundColor = UIColor.clearColor()

         return cell
    }

 }

And latest issuees after new collectionview codes.

SwiftDeveloper
  • 7,244
  • 14
  • 56
  • 85

3 Answers3

4
  1. You are setting cell.frame.size.width, CELL_WIDTH, layer.width inside statring and end of if sirano == 2 { loop. I removed the replica of this.
  2. As cell.label.font.fontWithSize is common for all. I put this in the beginning.
  3. label.backgroundColor is set thrice. I update your nested if satimdurum == 1 condition using ternary operator as below.
  4. You are not setting the values when myStringArrc[1] is not NULL. So I update the if-else conditional statement as below

    cell.label.backgroundColor = (satimdurum == 1) ? UIColor.redColor() : UIColor.orangeColor()

    cell.contentView.backgroundColor = (satimdurum == 1) ? UIColor.redColor() : UIColor.greenColor()

  5. I remove the static lines beneath above conditional loop, because these vales are getting set irrespective of upper conditions.

  6. Also move cell.label.text = "\(myStringArrc[1])-\(myStringArrc[5])" to right condition state. This value is being set on label all the time when sirano == 2
  7. Moving forward to else condition, again there is extra check of if satimdurum == 1. This condition is already checked in my above point no 4. So I am writing this check on initial stage of if-loop (if sirano == 1 || sirano == 2).

  8. Moving forward to next if myStringArrc[1] == "NULL" loop, I found that there is no any difference in check between this if-else and above if-else. You are doing the same thing when sirano == 2 or else. But there may be possibility that I missed some of your business logic here so I put the second condition as it is, and add the missed code in your else loop.

Updated code for cellForItemAtIndexPath:-

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! CustomCollectionViewCell

    cell.label.font.fontWithSize(12)
    cell.label.textColor = UIColor.whiteColor()

    if indexPath.item == 0 {
        cell.label.text = items[indexPath.section].base
        cell.label.frame.size.width = 30
        cell.label.frame.size.height = 30
        cell.label.layer.borderColor = UIColor.clearColor().CGColor
    } else {

        if let myStringc: String = items[indexPath.section].services[indexPath.item - 1] {
            var myStringArrc = myStringc.componentsSeparatedByString("*")

            let satimdurum:Int = Int(myStringArrc[3])!
            let sirano:Int = Int(myStringArrc[0])!

            if sirano == 1 || sirano == 2 {

                cell.label.backgroundColor = (satimdurum == 1) ?  UIColor.redColor() : UIColor.orangeColor()
                cell.contentView.backgroundColor = (satimdurum == 1) ?  UIColor.redColor() : UIColor.greenColor()
                cell.label.layer.borderColor = UIColor.blackColor().CGColor
                cell.alpha = 1

                if sirano == 2 {
                    cell.frame.size.width = 40
                    cell.layer.frame.size.width = 40
                    CELL_HEIGHT = 22.0
                    CELL_WIDTH = 40

                    if myStringArrc[1] == "NULL"  {
                        cell.label.alpha = 0
                        cell.label.backgroundColor = UIColor.clearColor()
                        cell.label.layer.borderColor = UIColor.clearColor().CGColor
                        cell.label.frame.size.width = 0
                        cell.label.frame.size.height = 0
                        cell.contentView.backgroundColor = UIColor.clearColor()
                    }else{
                        cell.label.alpha = 1
                        cell.label.backgroundColor = UIColor.redColor()//Or put orange color as per your logic based on myStringArrc
                        cell.label.frame.size.width = 40
                        cell.label.frame.size.height = 40
                        cell.contentView.backgroundColor = UIColor.redColor()//Or put orange color as per your logic based on myStringArrc
                        cell.label.text = myStringArrc[1]
                    }

                    cell.label.text = "\(myStringArrc[1])-\(myStringArrc[5])"
                }else{
                    if myStringArrc[1] == "NULL"  {
                        cell.label.alpha = 0
                        cell.label.backgroundColor = UIColor.clearColor()
                        cell.label.layer.borderColor = UIColor.clearColor().CGColor
                        cell.label.frame.size.width = 0
                        cell.label.frame.size.height = 0
                        cell.contentView.backgroundColor = UIColor.clearColor()
                    }else{
                        cell.label.text = myStringArrc[1]
                        cell.label.alpha = 1
                        cell.label.backgroundColor = UIColor.redColor()//Or put orange color as per your logic based on myStringArrc
                        cell.label.frame.size.width = 40
                        cell.label.frame.size.height = 40
                        cell.contentView.backgroundColor = UIColor.redColor()//Or put orange color as per your logic based on myStringArrc
                    }
                }
            }else{
                cell.label.alpha = 0
                cell.label.backgroundColor = UIColor.clearColor()
                cell.label.layer.borderColor = UIColor.clearColor().CGColor
                cell.label.frame.size.width = 0
                cell.label.frame.size.height = 0
                cell.contentView.backgroundColor = UIColor.clearColor()
                cell.alpha = 0
            }

        }
    }
    return cell
}
pkc456
  • 8,350
  • 38
  • 53
  • 109
  • that line cell.label.backgroundColor = (satimdurum == 1) ? : UIColor.redColor() : UIColor.orangeColor() gives Expected expression after '?' in ternary expression error – SwiftDeveloper Aug 19 '16 at 09:52
  • Ohh! I made a syntax mistake. Updated syntax:- `cell.label.backgroundColor = (satimdurum == 1) ? UIColor.redColor() : UIColor.orangeColor()` – pkc456 Aug 19 '16 at 09:55
  • all shows red background i will check if else s after i will write here okay. – SwiftDeveloper Aug 19 '16 at 10:53
  • In my answer, please check the point no 8. I think there may be some loophole because of same conditional checks. – pkc456 Aug 19 '16 at 11:19
  • i added your codes not bad but have issuees I ADDED TOP SIDE DID SELECT CODEs, my did select codes which cell user when click doing background blue and adding to array that cell after user again click same cell deleting it into array everything good but when i selected 4-5 cell after scrolled left and right side my all selected blue backgrounds missing after that your codes. – SwiftDeveloper Aug 19 '16 at 11:41
  • i edited and added your codes inside my question and i added issues image. – SwiftDeveloper Aug 19 '16 at 12:41
  • I debug your `didSelectItemAtIndexPath` function. You are setting the `contentView.backgroundColor` in this function itself. Thats why when cells are reusing then the color does not remain persistent. Try to reload [particular cell](http://stackoverflow.com/a/25707745/988169) and use the `koltuksiraid` in `cellForItemAtIndexPath ` – pkc456 Aug 19 '16 at 12:43
  • can you edit in your answer with that codes please ? i will try fastly ty. – SwiftDeveloper Aug 19 '16 at 12:44
  • that issues resolved after i will approve your answer. – SwiftDeveloper Aug 19 '16 at 13:17
  • after your codes have didselect bakcground missing when scrolled issue . – SwiftDeveloper Aug 20 '16 at 07:12
2

Did select cell (blue color) after scroll missing

Either you are adding or removing clickeditem from koltuksiraid array on didSelectItemAtIndexPath

koltuksiraid.removeAtIndex(index)
koltuksiraid.append(clickeditem)

When you scroll cells are reusing view and call cellForItemAtIndexPath. You should add a check to determine the cell color here for e.g

let color = koltuksiraid.contains(myStringc) ? UIColor(red: 62/256, green: 211/256, blue: 238/256, alpha: 1) : UIColor.orangeColor()

Scrolled after cell label goes right bottom

Cell label should be center position of the cell no mater what the cell size is. So do it form the storyboard. Delete all the label frame related code from your viewController

Some double width cell looking like this

This is a big issue. Cells are layout before cellForItemAtIndexPath. You can not change frame size of the cells here. Right place is prepareLayout() method of your CustomCollectionViewLayout. Here when you calculate position of each item you need to check which item should be double.

Delete all the cell frame related code from your cellForItemAtIndexPath. Create a protocol

protocol CustomCollectionViewDelegateLayout: NSObjectProtocol {

    func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, widthForItemAtIndexPath indexPath: NSIndexPath) -> CGFloat
}

In your viewController implemented this protocol method. Return value will be the width for the given indexPath

extension CustomCollectionViewController: CustomCollectionViewDelegateLayout {

    func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, widthForItemAtIndexPath indexPath: NSIndexPath) -> CGFloat {

        //from indexPath.section and indexPath.item identify double width item
        if sirano == 2 && satimdurum == 0 {
            return regularWidth * 2
        }
        return regularWidth
    }
}

Made a demo project with xcode 7.2 here at https://github.com/rishi420/UICollectionviewsample

Warif Akhand Rishi
  • 23,920
  • 8
  • 80
  • 107
0

Take a close look inside your implementation of this function in the CustomCollectionViewController class:

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {

You call this method to get a new cell:

let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! CustomCollectionViewCell

That's fine. But it doesn't give you a fresh blank cell every time. If the cell has been used before then you get it with the same colour and label text (and everything else) as last time.

So what you need to do is go through the logic in that function and make sure that every property you care about gets set every time. Take, for example, the last else block in the function - it doesn't set cell.label.text - and there's no guarantee that it's empty. That's why text and colours are jumping about as cells are redrawn by iOS.

Sometimes, if the cell logic is complex, its best to clean up the old formatting right after you dequeue the cell. Here's an example for a few properties:

    let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! CustomCollectionViewCell
    cell.label.text = nil
    cell.label.backgroundColor = UIColor.clearColor()
    cell.contentView.backgroundColor = UIColor.clearColor()
ncke
  • 1,084
  • 9
  • 14
  • thank for ideas i changed cell with reuseIdentifier variable but looking same. what can i do more ? – SwiftDeveloper Aug 17 '16 at 08:47
  • The problem isn't the reuse identifier. Suppose you had a bag with pieces of paper inside it. You take one out at random and write on it, then put it back in the bag. You keep doing it. Eventually you're going to pick out a piece of paper which already has writing on it? So, if you want to keep them clean then you have to rub out the old writing and replace it. That's how dequeueReusableCell works. You are re-using the cells, not getting fresh ones each time. – ncke Aug 17 '16 at 08:49
  • Try this. After the cell gets dequeued, straightaway on the next line set the cell.label.text to nil and set the background colour to clear. That way you'll know that those properties are getting set every time for every cell. See if that helps. – ncke Aug 17 '16 at 08:53
  • yeah can you give me sample code for integrate this ? – SwiftDeveloper Aug 17 '16 at 08:58
  • i added them but same :( not work when i scrolling left and right disappears labels. – SwiftDeveloper Aug 17 '16 at 09:23
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/121139/discussion-between-ncke-and-swiftdeveloper). – ncke Aug 17 '16 at 09:44