2017-12-18 178 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 
    } 
    } 

喲你必須在你的父類中使用這個委託方法。不在單元類中。