【问题标题】:Find the actual displayed number of items per row in a UICollectionView在 UICollectionView 中查找每行实际显示的项目数
【发布时间】:2021-08-26 09:55:48
【问题描述】:

我有一个 UICollectionView 矩形单元格,它们的尺寸大多是统一的,布局有一个股票 UICollectionViewFlowLayout

我正在尝试在应用程序的 Catalyst 版本中实现键盘箭头导航。左右都没有问题。这是一个完整的示例:

@objc func myRightKey() {
    var curr = glyphCollectionOutlet.indexPathsForSelectedItems?.first
    if curr == nil {curr = IndexPath(row: 0, section: 0)}
    if self.selectedCell == nil {self.selectedCell = curr} else {curr = self.selectedCell}
    let inSection = (curr!.section)
    // increment item in section up to max number of items
    let nextItem = curr!.item + 1
    let maxItem = glyphCollectionOutlet.numberOfItems(inSection: inSection) - 1
    let newItem = min(nextItem, maxItem)
    let newSelectPath = IndexPath(item: newItem, section: inSection)
    self.selectedCell = newSelectPath
    glyphCollectionOutlet.selectItem(at: newSelectPath, animated: true, scrollPosition: .centeredVertically)
    glyphCollectionOutlet.reloadData()
}

这里的问题是上下导航应该将选定的单元格直接放在起点的上方或下方。在 Mac Catalyst 中,嵌入了 collectionViewviewController 可以改变宽度,从而改变单元格/项目的数量连续。不幸的是,在 collectionView 中,IndexPath.row 似乎与 IndexPath.item 完全相同,与显示的行完全无关。

我需要计算下一个项目的 IndexPath,它应该距离当前选择 N 个项目。确实,我可以测量当前的 collectionView 宽度,但单元间距仍然是可变的。有没有办法动态计算或检测一行中显示的项目数,以便我可以计算 N

【问题讨论】:

    标签: ios swift uicollectionview uicollectionviewlayout mac-catalyst


    【解决方案1】:

    可能有办法做到这一点,但我相信还有更好的方法。

    为什么不取当前单元格的中心,将其y与项目高度偏移,然后检查哪个索引路径位于那里?

    let currentCenter = cell.center
    // Let's suppose you want to go downwards, just change to subtraction for going upwards
    let targetCenter = CGPoint(currentCenter.x, currentCenter.y + cell.bounds.height) // Or however you want to consider the item height
    let targetIndexPath = collectionView.indexPathForItemAtPoint(targetCenter)
    

    此外,这对于不统一的项目大小也应该很有效。

    【讨论】:

    • 太棒了!有一个小错误可以正常工作:调整后的目标 Y 值应该是 = CurrentY + bounds.Height/2 + 单元间间距的偏移量。非常感谢!非常聪明!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-04
    • 1970-01-01
    • 1970-01-01
    • 2020-06-26
    • 1970-01-01
    相关资源
    最近更新 更多