CollectionView:UIViewRepresentable + NavigationView

时间:2020-04-06 16:18:46

标签: ios swift uicollectionview swiftui uiviewrepresentable

我使用SwiftUI,这是UIViewRepresentable。我通过这种方式进行了CollectionView。当我尝试。在控制器中添加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")
        }
    }

基本上,它应该运作良好,但是我做错了什么?

1 个答案:

答案 0 :(得分:2)

您必须调用.edgesIgnoringSafeArea(.top),它将通过从collectionView中删除多余的空间来解决问题。

下面是更改后的代码。

struct CollectionContainer: View {

    var body: some View {

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

    }

}

希望它会对您有所帮助。