0

I am trying to add UILabels in the subView of my Collection Cell. But when I scroll to the other cell and come back all the UIlabels appear on both cells and some are written under the other..

I tried with collectionView.cellForItemAtIndexPath(indexPath) as? CollectionViewCell , but when I used it none UIlabel was displayed ( I tried with breaking points, it doesn't go after the if statement)

How can I fix it??

Thanks!!!

  class CollectionView: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate {

        var collection = [PFObject]()

        @IBOutlet weak var collectionView: UICollectionView!

        let sidePadding:CGFloat = 10

        var checkLocation: Bool = false

        override func viewDidLoad()
        {
            super.viewDidLoad();
            self.collectionView!.delegate = self
            self.collectionView!.dataSource = self

        }

        func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
            return 1
        }

        func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
            return self.collection.count
        }

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


            let cell = collectionView.dequeueReusableCellWithReuseIdentifier("CollectionCell", forIndexPath: indexPath) as! CollectionViewCell

            cell.layer.borderColor = UIColor.lightGrayColor().CGColor
            cell.layer.borderWidth = 0.5
            cell.layer.cornerRadius = 3

            let collectionViewWidth = self.collectionView.bounds.size.width - self.sidePadding * 2
            cell.frame.size.width = collectionViewWidth
            let collectionViewHeight = self.collectionView.bounds.size.height/4.5
            cell.frame.size.height = collectionViewHeight


            // Display the country name
            if let value = self.collection[indexPath.row]["Name"] as? String {
                cell.cellTitle.text = String(Int(indexPath.row)) + "." + value

            }

            let width = (cell.bounds.width - 94 - 4*3 - 60 - 20)/4
            let cellheight = CGFloat(6)
            let cellheight1 = CGFloat(6 + 12 + 2)

            var array = [String]()

            if let MWl = collection[indexPath.row]["MW"] as? Int
            {
                if MWl == 1 {

                    array.append("M")

                } else if MWl == 2 {

                    array.append("M")
                    array.append("W")

                }


            }

            if let JAl = collection[indexPath.row]["JA"] as? Int
            {
                if JAl == 1 {

                    array.append("Jy")

                } else if JAl == 2 {

                    array.append("Jy")
                    array.append("Ac")

                }

            }

            if let HK = collection[indexPath.row]["HK"] as? Int
            {
                if HK == 1 {

                    array.append("HB")

                } else if HK == 2 {

                    array.append("HB")
                    array.append("Ks")

                }
            }

            if let SSl = collection[indexPath.row]["SSl"] as? Int
            {
                if SSl == 1 {

                    array.append("AB")

                } else if SSl == 2 {

                    array.append("AB")
                    array.append("CD")

            }

            //I tried here too
            //  if let myCell = collectionView.cellForItemAtIndexPath(indexPath) as? CollectionViewCell

            if array.count <= 4 {
                for i in 0..<array.count {

                    let taille = CGFloat(i)
                    var si = CGFloat((1+i)*3 + 94 + 30)
                    let label = UILabel() as UILabel
                    label.frame = CGRectMake((si + width*taille), cellheight, width, 12)
                    label.textColor = UIColor(red: 0/255, green: 125/255, blue: 255/255, alpha: 1.0)
                    label.backgroundColor = UIColor.clearColor()
                    label.layer.borderWidth = 0.7
                    label.layer.borderColor = UIColor.lightGrayColor().CGColor
                    label.font = UIFont(name: "Futura-Medium", size: 9)
                    label.textAlignment = NSTextAlignment.Center
                    label.numberOfLines = 1
                    label.text = array[i]
                    label.layer.masksToBounds = true
                    label.layer.cornerRadius = 3.5
                    if let myCell = collectionView.cellForItemAtIndexPath(indexPath) as? CollectionViewCell {
                        myCell.contentView.addSubview(label)
                    }
                }

            } else {

                for i in 0...3 {

                    let taille = CGFloat(i)
                    var si = CGFloat((1+i)*3 + 94 + 30)
                    let label = UILabel() as UILabel
                    label.frame = CGRectMake((si + width*taille), cellheight, width, 12)
                    label.textColor = UIColor(red: 0/255, green: 125/255, blue: 255/255, alpha: 1.0)
                    label.backgroundColor = UIColor.clearColor()
                    label.layer.borderWidth = 0.7
                    label.layer.borderColor = UIColor.lightGrayColor().CGColor
                    label.font = UIFont(name: "Futura-Medium", size: 9)
                    label.textAlignment = NSTextAlignment.Center
                    label.numberOfLines = 1
                    label.text = array[i]
                    label.layer.masksToBounds = true
                    label.layer.cornerRadius = 3.5
                    if let myCell = collectionView.cellForItemAtIndexPath(indexPath) as? CollectionViewCell {
                        myCell.contentView.addSubview(label)
                    }
                }

                var j = 0 as Int
                for i in 4..<array.count {

                    let taille = CGFloat(j)
                    let si = CGFloat((1+j)*3 + 94 + 30)
                    let label = UILabel() as UILabel
                    label.frame = CGRectMake((si + width*taille), cellheight1, width, 12)
                    label.textColor = UIColor(red: 0/255, green: 125/255, blue: 255/255, alpha: 1.0)
                    label.backgroundColor = UIColor.clearColor()
                    label.layer.borderWidth = 0.7
                    label.layer.borderColor = UIColor.lightGrayColor().CGColor
                    label.font = UIFont(name: "Futura-Medium", size: 9)
                    label.textAlignment = NSTextAlignment.Center
                    label.numberOfLines = 1
                    label.text = array[i]
                    label.layer.masksToBounds = true
                    label.layer.cornerRadius = 3.5
                    if let myCell = collectionView.cellForItemAtIndexPath(indexPath) as? CollectionViewCell {
                        myCell.contentView.addSubview(label)
                    }
                    j = j + 1
                }

            }

            return cell
        }

    } 

EDIT

I tried to create the UILabel programmatically. But in that way I used the elements designed with the StoryBoard and the elements created programmatically. And actually I can't because of this :

     collectionView!.registerClass(RDCell.self, forCellWithReuseIdentifier: "Cell")

I create all the content of the cell programmatically ( the collectionView is created with the storyboard) and it works perfectly.

L.Vl
  • 113
  • 2
  • 14
  • because the cell is reused , add tags to label when cell is loads remove labels with specific tag, you can use viewwithtag method for it. – NSLog Mar 16 '16 at 20:27

2 Answers2

0

The cell is being reused, therefore you are always adding new labels each time cellForItemAtIndexPath is called. Just tag your labels like label.tag = 1 and when you dequeue the cell remove every subview with this tag, like

let cell = collectionView.dequeueReusableCellWithReuseIdentifier("CollectionCell", forIndexPath: indexPath) as! CollectionViewCell
for view in cell.subviews {
   if view.tag == 1 {
      view.removeFromSuperview()
   }
}

You will be always recreating the labels though, which is bad design. I suggest designing those labels on storyboard or if you insist on doing it in code keep optional references to the label in the cell to not recreate them each time cellForItemAtIndexPath is called.

FruitAddict
  • 2,042
  • 15
  • 16
  • Thanks @FruitAddict, I tried it, but when I move just a little bit the cell it removes all the labels. I would like to do it programmatically and not using UIStackView because I am targeting iOS8. I create 8 UILabels in my CollectionCell (var label : UILabel?...), Then I assign them a text value and a position reading to the array.count. But nothing is displayed.. Do you know what is going on? Thanks! – L.Vl Mar 17 '16 at 18:36
0

not recommended but you can do is, Add tag to each label like 1000 or something and find sub views of cell if any of subview tag matches with label tag remove that view

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

     for let labelIs in cell.subviews
        {
            if labelIs.tag == 1000
            {
                labelIs.removeFromSuperview()
            }
        }
      //some whare 
      var label = UILabel()
      label.tag = 1000
      return cell
}
NSLog
  • 649
  • 1
  • 5
  • 12
  • Thanks @NSLog, I tried it, but when I move just a little bit the cell it removes all the labels. I create 8 UILabels in my CollectionCell (var label : UILabel?...), Then I assign them a text value and a position reading to the array.count. But nothing is displayed.. Do you know what is going on? Thanks! – L.Vl Mar 17 '16 at 18:37
  • labels are never appearing ?,this way it should work. – NSLog Mar 17 '16 at 19:43
  • Nothing appears.. I don't get it at all.. I added my script tin the EDIT. Do you see where is the mistake? – L.Vl Mar 17 '16 at 20:11
  • you are using custom cell so you should not remove labels from cell,if you what that kind of affect you can hide and unhide the labels . – NSLog Mar 17 '16 at 20:14
  • first remove labelIs.removeFromSuperview() this code and try – NSLog Mar 17 '16 at 20:16
  • Ok I add screenshots of the result. I tried with and without : for label in cell.subviews { if label.tag == 1000 { label.hidden = true } } But as you can see, I am still rewriting – L.Vl Mar 17 '16 at 20:41
  • are you adding tag to label like label.tag = 1000 or you can add in xib also ,the labels which are using should be label.hidden = false,please check . – NSLog Mar 17 '16 at 21:04
  • Yes I added label.tag == 1000 and I just tried with label.hidden=false when I generate the label, no improvement.. I will try with xib! We keep in touch, Thanks a lot! – L.Vl Mar 17 '16 at 21:50
  • I figured out how to do it. I used elements designed with the StoryBoard and elements created programmatically. And actually I can't because of this (link the elements created programmatically on RDCell) : collectionView!.registerClass(RDCell.self, forCellWithReuseIdentifier: "Cell") I create all the content of the cell programmatically ( the collectionView is created with the storyboard) and it works perfectly. – L.Vl Mar 21 '16 at 11:23