簡體   English   中英

如何防止出隊的集合視圖單元格彼此重疊?

[英]How to prevent dequeued collection view cells from overlapping each other?

我一直在嘗試建立一個集合視圖,在該視圖中,我讓用戶提交幾個要放入數組中的字符串,然后通過集合視圖的cellForItemAt函數進行回調。 但是,每當我在集合視圖的頂部添加一行時,它就會在最后一個單元格標簽的頂部逐字地添加單元格標簽,因此它們像這樣堆疊 請注意,我添加的每個新單詞如何在渲染中包括所有其他先前的單詞。

我在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刪除單元格,並且這些單元格不會再次消失。 任何幫助表示贊賞!

這是我在自定義集合視圖單元格實現中包含的代碼,以防引起錯誤

為此,將這些功能粘貼到您的項目中

   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
}

您可以使用這些值:)

可以使用UITableView輕松實現。 因此,請嘗試使用UITableView而不是UICollectionView。

我多次遇到相同的問題。 大多數時候,向UICollectionViewCell添加“配置”代碼可以達到目的。 也許將“ interestField.text”和任何其他配置移至您的單元格即可解決此問題。 有時我仍然會得到那些重疊或錯誤的配置。 希望能幫助到你

好像您每次設置文本都在添加一個新標簽。 如果要延遲加載UILabel,則需要添加lazy

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

不過,我不會這樣做,我會創建對標簽的引用

weak var interestLabel: UILabel!

然后在您的setupViews方法中添加標簽

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM