2017-07-13 154 views
0

我正在使用一个collectionview和第一个数据加载工作正常。当数据第二次加载标签重叠时会发生问题,因为旧标签似乎仍然存在。 以下是我的收藏查看代码,在此先感谢。UICollectionView重叠标签

  func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { 
       let customCell = collectionView.dequeueReusableCell(withReuseIdentifier: "customCellIdentifier", for: indexPath) 
       customCell.layer.borderColor = UIColor.black.cgColor 
       customCell.layer.borderWidth = 1 


    // changed these lines here 
       if cellsLabels[indexPath.row] != nil { 
        customCell.willRemoveSubview(cellsLabels[indexPath.row]!) 
       } 
    //to these lines here and the problem was solved 
      let maybe = customCell.subviews 

      for i in 0 ..< maybe.count { 
       maybe[i].removeFromSuperview() 
      } 
       let c 

ommentLabel = UILabel() 
      commentLabel.text = commentsArray[indexPath.row] 
      commentLabel.frame = CGRect(x: 0, y: 50, width: 200, height: 30) 
      customCell.addSubview(commentLabel) 

      self.cellsLabels[indexPath.row] = commentLabel 

      if indexPath.row == commentLoadTracker*10 - 1 { 
       print("working doomfist") 
      } 

      return customCell 
     } 

     func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { 

      return commentsArray.count 
     } 

     func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { 
      var cellSize = CGSize() 
      cellSize.width = self.commentView.frame.width 
      cellSize.height = 100 
      return cellSize 
     } 
+0

你并不需要用你的结果更新问题。这可能会带来问题的明确性。此外,你可以像这样循环访问子视图:'在customCell.subviews中查看',那么你不必创建一个新的数组。 –

回答

1

customCell.willRemoveSubview

要调用willRemoveSubiew代替removeFromSuperview

if cellsLabels[indexPath.row] != nil { 
    cellsLabels[indexPath.row]!.removeFromSuperview() 
} 

无需调用willRemoveSubview,呼吁的UIKit为你,它只存在这样它可以是

在子视图从视图中删除之前,由子类重写以执行其他操作。

+0

还有你!问题解决了,还有另一个小问题,但基本上把这个抓起来感谢了! – Blue

+0

@AaronMann这没问题!赞成票和标记它接受,将不胜感激! –