我确实做到了。但不确定这是否是正确的解决方案。如果有人有更好的解决方案,请添加您的答案。所以我创建了一个UICollectionViewCell
子类。
final class HostingCollectionViewCell: UICollectionViewCell {
func host<Content: View>(_ hostingController: UIHostingController<Content>) {
backgroundColor = .clear
hostingController.view.translatesAutoresizingMaskIntoConstraints = false
hostingController.view.backgroundColor = .clear
addSubview(hostingController.view)
let constraints = [
hostingController.view.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 0),
hostingController.view.leftAnchor.constraint(equalTo: contentView.leftAnchor, constant: 0),
hostingController.view.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: 0),
hostingController.view.rightAnchor.constraint(equalTo: contentView.rightAnchor, constant: 0),
]
NSLayoutConstraint.activate(constraints)
}
}
并像使用它一样..
func makeUIView(context: Context) -> UICollectionView {
let collectionView = UICollectionView(
frame: .zero,
collectionViewLayout: MyCustomCollectionViewLayout()
)
collectionView.register(HostingCollectionViewCell.self, forCellWithReuseIdentifier: "HostingCell")
let dataSource = UICollectionViewDiffableDataSource<Section, Member>(collectionView: collectionView) { collectionView, indexPath, member in
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "HostingCell", for: indexPath) as? HostingCollectionViewCell
for subview in cell?.contentView.subviews ?? [] {
subview.removeFromSuperview()
}
let swiftUIView = SomeSwiftUIView()
.onTapGesture {
// Equivalent of didTapItemAt...
}
cell?.host(UIHostingController(rootView: firefighterView))
return cell
}
context.coordinator.dataSource = dataSource
collectionView.clipsToBounds = false
collectionView.backgroundColor = .clear
collectionView.showsVerticalScrollIndicator = false
// Populated Datasource
return collectionView
}
这makeUIView
是struct SwiftUICollectionView: UIViewRepresentable
观点的一部分。