![](/img/trans.png)
[英]How to reload collectionview in UIViewRepresentable SwiftUI
[英]CollectionView : UIViewRepresentable + NavigationView
我使用 SwiftUI,這是 UIViewRepresentable。 我通過這種方式做了 CollectionView。 當我嘗試。 在 controller 中添加 NavigationView,它可以工作,但不正確。 當我滾動時,collectionView 和 navigationView 之間的空間被釋放。
@State var data:[Int] = [1,2,3,4,5,6,7,8,9,0,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30]
var didSelectItem: ((_ indexPath: IndexPath)->()) = {_ in }
var didSelectObject: ((_ boject: Recipe)->()) = {_ in }
func makeUIView(context: Context) -> UICollectionView {
let layout = UICollectionViewFlowLayout()
let collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout)
collectionView.translatesAutoresizingMaskIntoConstraints = false
collectionView.dataSource = context.coordinator
collectionView.delegate = context.coordinator
collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "myCell")
collectionView.backgroundColor = .clear
collectionView.alwaysBounceVertical = true
return collectionView
}
func updateUIView(_ uiView: UICollectionView, context: Context) {
uiView.reloadData()
}
func makeCoordinator() -> Coordinator {
return Coordinator(data: data)
}
class Coordinator: NSObject, UICollectionViewDelegate, UICollectionViewDataSource {
var data: [Int]
init(data: [Int]) {
self.data = data
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return data.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "myCell", for: indexPath)
let textLable = UILabel()
textLable.text = String(data[indexPath.row])
cell.addSubview(textLable)
cell.backgroundColor = .red
return cell
}
//something more
private func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath)
{
print("User tapped on item \(indexPath.row)")
}
}
這是用 NavigationView 表示集合視圖的代碼:
VStack {
NavigationView {
HStack {
MenuController()
}.navigationBarTitle("Menu")
}
}
基本上,它應該工作得很好,但我做錯了什么?
你必須調用.edgesIgnoringSafeArea(.top)
,它會通過從你的 collectionView 中刪除額外的空間來解決問題。
以下是更改后的代碼。
struct CollectionContainer: View {
var body: some View {
VStack {
NavigationView {
HStack {
MenuController()
}.navigationBarTitle("Menu")
.edgesIgnoringSafeArea(.top) // Trick
}
}
}
}
希望它會幫助你。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.