集合视图:UIViewRepresentable + NavigationView

CollectionView : UIViewRepresentable + NavigationView

我使用 SwiftUI,这是 UIViewRepresentable。 CollectionView我就是这样搞的。当我尝试时。在控制器中添加 NavigationView,它可以工作,但不正确。当我滚动时,collectionView 和 navigationView 之间的 space 被释放了。

@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 中删除多余的 space 来达到目的。

下面是您的代码更改后的样子。

struct CollectionContainer: View {

    var body: some View {

        VStack {
            NavigationView {
            HStack {
                MenuController()
            }.navigationBarTitle("Menu")
                .edgesIgnoringSafeArea(.top) // Trick
            }
        }

    }

}

希望对您有所帮助。