【问题标题】:UICollectionView cell UI with horizontal paging randomly disappearing水平分页随机消失的 UICollectionView 单元格 UI
【发布时间】:2018-11-15 21:05:06
【问题描述】:

我有一个 UICollectionView,它一次显示一个单元格,在启用分页的情况下水平滚动。每个单元格都有一些 UI(视图、文本视图)。

用户可以通过三种方式浏览单元格。 (1) 用户点击 UIButtons 以使用 collectionView.scrollToItem 在单元格之间左右导航,(2) 用户通过点击另一个 UIButton 在数组末尾创建一个新单元格,(3) 用户使用 scrollViewWillEndDragging 滚动。

问题是,在情况 (1) 和 (2) 中,有时单元格 UI 会消失。从一个单元格到另一个单元格来回导航将再次将其带回来。这似乎是随机的。

有两种方法可以隔离问题,但仍然不知道如何找到解决方法:(a) 如果我在每次导航之间将所有 textViews 完全设置为 endEditing(true),则 UI 不会消失 (这意味着键盘在重新出现之前完全消失)。 (b) 如果用户只使用滚动方法从一个单元格导航到另一个单元格,它永远不会消失 - 只要使用任何按钮,UI 就会再次消失。

我尝试使用 prepareForReuse() 方法在自定义 UICollectionView 单元格中重置 UI,但这似乎没有帮助。

这可能与我之前问过的another question有关。

感谢任何指点!

这就是我将单元格出列的方式:

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let addCardCell = collectionView.dequeueReusableCell(withReuseIdentifier: "CardCell", for: indexPath) as! AddCardCell

    addCardCell.autoSaveCard = autoSaveCards[indexPath.item]
    return addCardCell
}

这是我的滚动方法:

func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {
    autoSaveCard()

    let x = targetContentOffset.pointee.x
    currentCardIndex = Int(x / view.frame.width)
    updateKeyboardInputLabelsAndButtons()

    setNewFirstResponder()
}

按钮方法之一:

@objc func handleAddCell() {
    autoSaveCard()
    createEmptyAutoSaveCard()

    let newIndexPath = IndexPath(item: autoSaveCards.count - 1, section: 0)
    collectionView.insertItems(at: [newIndexPath])

    collectionView.scrollToItem(at: newIndexPath, at: .left, animated: false)
    currentCardIndex = autoSaveCards.count - 1

    DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
        self.setNewFirstResponder()
    }
}

【问题讨论】:

  • 尝试在集合视图的willDisplayCell方法中调用cell.layoutIfNeeded()
  • 谢谢!不幸的是,这并没有做到。

标签: ios swift uicollectionview uitextview cell


【解决方案1】:

试试这个。保留一个数组来存储您在控制器中创建的单元格(比如cellsArray)。如果元素存在于该indexPath.row,则从该数组返回。

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    if cellsArray[indexPath.row] != nil {
        return cellsArray[indexPath.row]
    }

    let addCardCell = collectionView.dequeueReusableCell(withReuseIdentifier: "CardCell", for: indexPath) as! AddCardCell

    addCardCell.autoSaveCard = autoSaveCards[indexPath.item]
    cellsArray.append(addCardCell)
    return addCardCell
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-07
    • 2023-03-25
    • 2012-11-01
    • 2019-12-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多