Надежно ли использовать UICollectionView indexPath для доступа к словарным ключам?
Я пытаюсь использовать IndexPath текущего CollectionViewcell для доступа к данным из словаря. Ключи словаря имеют тип Int. Это CollectionView имеет ячейки "полной страницы", что означает, что каждая ячейка занимает всю область просмотра, где я использую горизонтальную прокрутку (с включенной подкачкой) для навигации между ячейками.
Словарь это:
var dataFromServer: [Int: [VillageFestival]]?
Каждый CollectionViewCell имеет TableView внутри, где я планирую иметь переменное количество строк, в зависимости от того, сколько предметов есть в [VillageFestival]
Однако в CollectionView cellForItemAt indexPath
поведение метода вызывает некоторые проблемы, так как печать indexPath.item или установка его в качестве заголовка моего navigationController возвращает странные, но "понятные" результаты, учитывая, как я думаю, работает dequeueReusableCell?...
Пример: текущий индекс равен 0. Когда я прокручиваю вправо, текущий индекс теперь равен 2. Если я перехожу на страницу 6 и затем на одну страницу назад, текущий индекс показывает 3.
Я изменил ключи моего словаря с Date на String, а теперь на Int, чтобы упростить логику. Но проблема остается. Я использую глобальный pageIndex: Int
это обновляется внутри CollectionView cellForItemAt
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
pageIndex = indexPath.item
self.navigationController?.navigationBar.topItem?.title = String(pageIndex)
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "collectionViewCell", for: indexPath) as! CollectionViewCell
// CollectionViewCell resize to CollectionView Bounds
cell.tableViewCellOffsets = (UIApplication.shared.statusBarFrame.size.height + (self.navigationController?.navigationBar.frame.height ?? 0.0) , self.tabBarController?.tabBar.frame.height ?? 0)
return cell
}
В Tableview numberOfRowsInSection я использую pageIndex для доступа к значениям словаря.
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
guard let festivals = dataFromServer?[pageIndex] else {return 0}
return festivals.count
}
С моим текущим кодом приложение отображает 0 строк для некоторых страниц и 1 строку для других. Я предполагаю, что cellForItemAt collectionView вызывается до (также возможно после?) Методов tableView, и это делает использование глобального pageIndex ненадежным...
Спасибо!
1 ответ
Попробуйте эту игровую площадку, она может помочь вам:
import UIKit
import PlaygroundSupport
class Cell: UICollectionViewCell, UITableViewDataSource {
var data: [Int]! = [] {
didSet {
tableView.reloadData()
}
}
private let tableView: UITableView
override init(frame: CGRect) {
tableView = UITableView(frame: .zero, style: .plain)
super.init(frame: frame)
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "Cell")
tableView.dataSource = self
tableView.translatesAutoresizingMaskIntoConstraints = false
contentView.addSubview(tableView)
NSLayoutConstraint.activate([
tableView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor),
tableView.trailingAnchor.constraint(equalTo: contentView.trailingAnchor),
tableView.topAnchor.constraint(equalTo: contentView.topAnchor),
tableView.bottomAnchor.constraint(equalTo: contentView.bottomAnchor)
])
}
required init?(coder aDecoder: NSCoder) {
fatalError()
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return data.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
cell.textLabel?.text = String(data[indexPath.item])
return cell
}
}
class VC: UICollectionViewController {
let data = [
0: [1, 2, 3, 4, 5],
1: [6, 4],
2: [5, 5, 5, 5, 6],
3: [9, 9, 8, 4, 5, 5, 5]
]
override init(collectionViewLayout layout: UICollectionViewLayout) {
super.init(collectionViewLayout: layout)
collectionView.isPagingEnabled = true
collectionView.register(Cell.self, forCellWithReuseIdentifier: "Cell")
}
required init?(coder aDecoder: NSCoder) {
fatalError()
}
override func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return data.count
}
override func viewDidLayoutSubviews() {
(collectionViewLayout as? UICollectionViewFlowLayout)?.itemSize = collectionView.bounds.size
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! Cell
cell.data = data[indexPath.item]
return cell
}
}
let layout = UICollectionViewFlowLayout()
layout.scrollDirection = .horizontal
PlaygroundPage.current.liveView = VC(collectionViewLayout: layout)