【发布时间】:2020-04-25 11:06:42
【问题描述】:
首先,我知道有一些选项可以使用 SwiftUI 列表等...获得类似的效果。但我需要 UICollectionView 的自动滚动功能,所以我真的很想实现一个“老派”版本。我什至不想要理想的组合布局版本。
我当前的代码如下所示:
import SwiftUI
struct CollectionView: UIViewControllerRepresentable {
private var isActive: Binding<Bool>
private let viewController = UIViewController()
private let collectionController: UICollectionView
init(_ isActive: Binding<Bool>) {
self.isActive = isActive
self.collectionController = UICollectionView(frame: CGRect(x: 0, y: 0, width: 100, height: 200), collectionViewLayout: UICollectionViewFlowLayout())
}
func makeUIViewController(context: UIViewControllerRepresentableContext<CollectionView>) -> UIViewController {
return viewController
}
func updateUIViewController(_ uiViewController: UIViewController, context: UIViewControllerRepresentableContext<CollectionView>) {
if self.isActive.wrappedValue && collectionController.delegate == nil { // to not show twice
collectionController.delegate = context.coordinator
collectionController.dataSource = context.coordinator
}
}
func makeCoordinator() -> Coordintor {
return Coordintor(owner: self)
}
final class Coordintor: NSObject, UICollectionViewDelegate, UICollectionViewDataSource {
weak var viewController:UIViewController?
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 3
}
var cellId = "Cell"
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath)
return cell
}
// works as delegate
let owner: CollectionView
init(owner: CollectionView) {
self.owner = owner
}
}
}
不幸的是,我得到的只是预览中的空白屏幕。现在,如果我可以显示大量红色方块,我可以滚动浏览并自动滚动到底部 onAppear,那将是理想的。
谢谢!
【问题讨论】:
标签: swift uicollectionview swiftui