2017-12-18 176 views
1

我有一个集合视图。我想创建收集视图的单元格作为标记。我已经写了,但它并没有计算宽度&也离开了,单元格之间的距离很近。请告诉我如何改进它?无法在swift中创建TAGVIEW?

extension StoreItemCell:UICollectionViewDelegate { 
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize { 

     let width = CGSize(
     return self.sizingCell!.systemLayoutSizeFitting(UILayoutFittingCompressedSize) 
    }   
} 



override func awakeFromNib() { 
     super.awakeFromNib() 
     // Initialization code 
     self.tagsCollectionView.delegate = self 
     self.tagsCollectionView.dataSource = self 
     let cellNib = UINib(nibName: Titles.CellIdentifier.TagCell, bundle: nil) 
     self.tagsCollectionView.register(cellNib, forCellWithReuseIdentifier: Titles.CellIdentifier.TagCell) 
     self.tagsCollectionView.backgroundColor = UIColor.clear 
     self.sizingCell = (cellNib.instantiate(withOwner: nil, options: nil) as NSArray).firstObject as! TagCell? 
     self.flowLayout.sectionInset = UIEdgeInsetsMake(8, 8, 8, 8) 
     self.flowLayout.minimumInteritemSpacing = 15 
    } 

请告诉我如何改善它。我附上了我设计的截图。

enter image description here

回答

1

添加这一项

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { 
     let Labell : UILabel = UILabel() 

     Labell.text = self.TagsArray[indexPath.item] as? String 
     let labelTextWidth = Labell.intrinsicContentSize.width 
     return CGSize(width: labelTextWidth + 10, height: 30) 


    } 

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell 
{ 
} 
+0

我不认为创建这样的标签是个好主意,因为我会在内存中创建如此多的标签对象。如果有20个单元格,每个单元格最多可以有10个标签,因此只会为一个屏幕创建200个对象,这可能会导致内存问题 – Techiee

+0

@DhirajKumar。我在说要创建一个标签多次使用它 –

+0

但是标签的创建次数与cellforitem的调用次数相同 – Techiee

0

你的代码中创建的UILabel应该在你的父类,而不是在细胞类,

extension YourViewController:UICollectionViewDelegate { 
    func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize { 

      return //YourCellSize here 
    } 
    } 

哟你必须在你的父类中使用这个委托方法。不在单元类中。