ios - 集合视图:UIViewRepresentable + NavigationView
问题描述
我使用 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")
}
}
基本上,它应该工作得很好,但我做错了什么?
解决方案
你必须打电话.edgesIgnoringSafeArea(.top)
,它会通过从你的collectionView中删除额外的空间来解决问题。
以下是更改后的代码。
struct CollectionContainer: View {
var body: some View {
VStack {
NavigationView {
HStack {
MenuController()
}.navigationBarTitle("Menu")
.edgesIgnoringSafeArea(.top) // Trick
}
}
}
}
希望它会帮助你。
推荐阅读
- c - “良性”数据竞赛真的是良性的吗?
- javascript - 将函数结果分配给变量
- python - pandas:如何查看(参数)字符串是否在 pandas 元素中的字符串列表中(类似于反向 isin)
- php - 已弃用:strpos():将来非字符串指针将被解释为字符串。使用显式 chr() 调用来保留当前行为
- python - Python:列表总是附加相同的元素
- linux-device-driver - 我为 USB 键盘编写什么类型的驱动程序?
- crystal-reports - 根据参数输入(开始号和结束号)在水晶报表中创建序列号,无需连接数据库
- macos - 拖放 DMG 应用程序包的根所有权
- python - OpenCV 和 Python 代码错误帽未定义...但
- yaml - 在具有多阶段管道的 Azure DevOps 中,如何手动部署到环境中?