arrays - 将 IndexPath.row 转换为二维数组

标签 arrays swift uicollectionview uicollectionviewcell

我有一个数组,用于通过 Collection View 创建网格。为了在 collectionView 中提供 numberOfItemsInSection,我正在执行 row.count * row.count 来获取 8x8 网格和 64 个单元格。我的问题是我希望能够通过行和列而不是indexPath.row 访问和操作这些单元格。

因此,如果我想要第 5 个单元格,而不是在 IndexPath.row 中获取 #4,我希望能够执行以下操作:row[0][4]。关于如何将 IndexPath.row 转换为二维数组有什么建议吗?

var row = [[Int]]()
let column: [Int]

init() {
    self.column =  [1, 2, 3, 4, 5, 6, 7, 8] 
}

func createGrid() {
    for _ in 1...8 {
        row.append(column)
    }
}

the blue squares/cells are the cells that I want the row and columns for

最佳答案

为什么不简单地使用 8 个部分和 8 行,这就是 IndexPath 的设计目的

var grid = [[Int]]()

override func viewDidLoad() {
    super.viewDidLoad()
    for _ in 0..<8 {
        grid.append([0,1,2,3,4,5,6,7])
    }
}

func numberOfSections(in collectionView: UICollectionView) -> Int {
    return grid.count
}

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return grid[section].count
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! CollectionViewCell
    cell.label.text = "\(indexPath.section)/\(indexPath.row)"
    return cell
}

enter image description here

关于arrays - 将 IndexPath.row 转换为二维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55210544/

相关文章:

python - 将元素从for循环Python 3放入新数组中

Java : Taking 2 array find if the element that exists in both array return true if exist else false

ios - Stripe Basic PaymentIntent 确认付款错误

swift - 在 uicollectioncontroller 和 viewcontroller 之间传递单元格索引

ios - 如果我使用 unwindSegue 从屏幕 A 转到 B 再回到 B,如何返回到我的主显示器 (A)

mysql - 使用 MySQL 获取行的 JSON 数组

iphone - UICollectionView - 类似 iOS7 日历的缩放过渡

swift - iOS13 UICollectionViewFlowLayout 子类不接收 collectionView 框架更改

ios - 从 UICollectionView 中删除一个项目

javascript - 使用 Lodash 查找 [] 数组内 JSON 数组的索引