我必须更换一个现有的 SwiftUI List
观点的百分比 UICollectionView
(因为应用程序的设计已经更新,而新的设计对SwiftUI来说非常复杂,所以必须作为一个自定义的应用程序来实现。UICollectionViewFlowLayout
)
所以视图(现在将成为(或部分)UICollectionViewCell)已经在SwiftUI中实现了,我不想在Swift中重新编写它们。视图在写下Layout Code方面很复杂,显然用SwiftUI很容易。
我可以找到一些帮助,包装一个集合视图,如 这个 但如何在UICollectionViewCell中托管现有的swift ui视图却很少。
任何帮助suggestionslinks将被感激。
谅谅
我确实做到了。但不知道这是不是正确的解决方案。如果有人有更好的解决方案,请添加你的答案。所以我创建了一个 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
观点: