以编程方式将UILabels添加到Collection Cell,快速

时间:2016-03-16 20:04:57

标签: ios swift uicollectionview uicollectionviewcell uicollectionreusableview

我正在尝试在收集单元格子视图中添加UILabel。 但是当我滚动到另一个单元格并返回时,所有UIlabels都出现在两个单元格上,而另一些则写在另一个单元格下面。

我尝试使用collectionView.cellForItemAtIndexPath(indexPath) as? CollectionViewCell,但是当我使用它时没有显示UIlabel (我尝试使用断点,它不会在if语句之后)

我该如何解决?

感谢!!!

  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
        }

    } 

修改

我尝试以编程方式创建UILabel。但是通过这种方式,我使用了StoryBoard设计的元素和以编程方式创建的元素。实际上我不能因为这个:

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

我以编程方式创建单元格的所有内容(使用故事板创建collectionView)并且它完美地运行。

2 个答案:

答案 0 :(得分:0)

正在重复使用单元格,因此每次调用cellForItemAtIndexPath时都会添加新标签。只需标记label.tag = 1之类的标签,当您将单元格出列时,请使用此标记删除每个子视图,例如

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

你总是会重新创建标签,这是糟糕的设计。我建议在故事板上设计这些标签,或者如果你坚持在代码中这样做,请保留对单元格中标签的可选引用,以便每次调用cellForItemAtIndexPath时都不重新创建它们。

答案 1 :(得分:0)

不推荐,但你可以这样做, 将标签添加到每个标签(如1000或其他),如果任何子视图标签与标签标签匹配,则删除该视图

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
}
相关问题