2017-07-16 99 views
0

我一直在試圖設置一個集合視圖,我有用戶提交幾個字符串,我拋出一個數組並通過集合視圖的cellForItemAt函數回調。但是,無論何時將一行添加到集合視圖的頂部,它都會在最後一個單元標籤的頂部添加單元格標籤,因此they stack like this。請注意,我添加的每個新單詞都包含渲染中的所有其他單詞。如何防止出列集合視圖單元彼此重疊?

我在cellForItemAt代碼是

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

    if let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "InterestsCell", for: indexPath) as? InterestsCell { 
     cell.interestLabel.text = array[indexPath.row] 
     return cell 
    } else { 
     return UICollectionViewCell() 
    } 
} 

,並按下添加按鈕時,我的代碼是

func addTapped() { 
    let interest = interestsField.text 
    array.insert(interest!, at: 0) 
    interestsField.text = "" 

    collectionView.reloadData() 
} 

我不知道發生了什麼事。我到處尋找並嘗試使用prepareForReuse(),但它似乎沒有工作。我後來嘗試通過調用didSelect來刪除單元格,單元格不會再次消失。任何幫助表示讚賞!

This is the code I have in my custom collection view cell implementation in the event that this is causing the error

+0

我建議使用視圖調試器來確定問題是什麼(例如重疊標籤,重疊單元格或重疊的集合視圖)。你知道視圖層次結構是什麼樣子,這將縮小你的研究範圍。 – Rob

+0

@Rob謝謝Rob,這讓我走上了正軌。出於某種原因,它每創建一個集合視圖的新實例,我都會添加一個新字符串,以便將每個集合疊加在一起。 –

+0

是的,現在你可以追蹤你添加重複集合視圖的位置。但目前爲止,您還沒有與我們分享過的代碼。祝你好運! – Rob

回答

0

這可以使用的UITableView容易地實現。所以嘗試使用UITableView而不是UICollectionView。

0

我多次遇到同樣的問題。大多數時候,向UICollectionViewCell添加「配置」代碼的確有竅門。也許將你的「interestField.text」和其他配置移動到你的單元格將會解決這個問題。有時我仍然會遇到重疊或錯誤的配置。希望它可以幫助

+0

有一秒鐘我確信你是對的,所以我在單元中實現了一個配置功能,但它仍然沒有工作。 –

1

爲此貼上這些功能在您的項目

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat { 
    return 1 
} 

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat { 
    return 1 
} 

你可以玩的價值:)

+0

不幸的是,這並沒有解決問題。 –

0

它看起來像你每次你設定的時間添加新標籤文本。如果你想懶洋洋地加載的UILabel你需要添加lazy

lazy var interestLabel: UILabel = { 
    ... 
}() 

我不會做它,雖然這樣,我將創建一個參考標籤

weak var interestLabel: UILabel! 

然後在添加標籤你的setupViews方法

func setupViews() { 
    ... 
    let interestLabel = UILabel() 
    ... 
    contentView.addSubview(interestLabel) 
    self.interestLabel = interestLabel 
}