这个问题在这里已经有答案:
Passing data between view controllers(45个答案)
两天前关门了。
在单元格中单击后,我无法移动到另一个ViewController
。
我想做的是:
1.在单元格中单击后,移动到另一个ViewController
,
1.从拾取的小区发送url
到第二个ViewController
,用于下载其中的新数据。
我的CollectionView
看起来是这样的:
private func setupCollectionView() {
let layoutConfig = UICollectionLayoutListConfiguration(appearance: .insetGrouped)
let listLayout = UICollectionViewCompositionalLayout.list(using: layoutConfig)
collectionView = UICollectionView(frame: view.bounds, collectionViewLayout: listLayout)
view.addSubview(collectionView)
collectionView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
collectionView.topAnchor.constraint(equalTo: view.layoutMarginsGuide.topAnchor, constant: 0.0),
collectionView.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 0.0),
collectionView.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: 0.0),
collectionView.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: 0.0),
])
//MARK: - registration of cell with data from ViewModel
let cellRegistration = UICollectionView.CellRegistration<UICollectionViewListCell, PokemonResults> { (cell, indexPath, item) in
var content = cell.defaultContentConfiguration()
content.text = item.name
content.secondaryText = item.url
cell.contentConfiguration = content
}
dataSource = UICollectionViewDiffableDataSource<Section, PokemonResults>(collectionView: collectionView) {
(collectionView: UICollectionView, indexPath: IndexPath, identifier: PokemonResults) -> UICollectionViewCell? in
let cell = collectionView.dequeueConfiguredReusableCell(using: cellRegistration, for: indexPath, item: identifier)
cell.accessories = [.disclosureIndicator()]
return cell
}
setupViewModel()
}
我的setupViewModel
是这样的:
private func setupViewModel() {
pokedexListVM.$pokemons
.receive(on: RunLoop.main)
.sink(receiveValue: { [weak self] _ in
self?.collectionView.reloadData()
}).store(in: &subscriptions)
self.snapshot = NSDiffableDataSourceSnapshot<Section, PokemonResults>()
self.snapshot.appendSections([.main])
self.snapshot.appendItems(self.pokedexListVM.pokemons, toSection: .main)
dataSource.apply(snapshot, animatingDifferences: false)
}
如何使用delegate
对CollectionView
进行那种编码?
1条答案
按热度按时间e4yzc0pl1#
首先,让我们稍微修改一下
setupViewModel()
。其次,假设包含集合视图的控制器称为
CurrentViewController
。使您的CurrentViewController
符合UICollectionViewDelegate
并实现collectionView(_:didSelectItemAt:)
,您可以阅读有关here的内容。它可能看起来像这样:并且不要忘记将您的控制器设置为
setupCollectionView()
中集合视图的委托,就像collectionView.delegate = self
一样