SwiftUI-如何停止ScrollView在其他视图后面接收水龙头

问题描述

我在LazyVStack内有一个ScrollView,它位于一个较小的视图(图像中的黄色视图)下方。

enter image description here

问题在于,当向上滚动网格时,单元格仍然可以通过黄色视图接收水龙头,这是我真正不想要的。我想在该视图中进行搜索TextField,触摸变得混乱,用户体验一团糟。在示例代码中,我添加了一个按钮以交换到List,以检查其是否具有相同的滚动问题。不是。

import SwiftUI

struct ContentView: View {
    
    @State private var useList = false
    @State private var gridLayout: [GridItem] = [GridItem(.flexible()),GridItem(.flexible()),GridItem(.flexible())]
    
    var data = (0...249).map { "\($0)" }
    
    var body: some View {
        NavigationView {
            VStack {
                TopInfoPane()
                if useList {
                    List(data,id: \.self) { item in
                        NavigationLink(destination: Text(item)) {
                            Text(item)
                        }
                    }
                } else {
                    ScrollView {
                        LazyVGrid(columns: gridLayout,alignment: .center,spacing: 8) {
                            ForEach(data,id: \.self) { item in
                                NavigationLink(destination: Text(item)) {
                                    Cell(item: item)
                                }
                            }
                        }
                    }
                }
            }.navigationBarTitle("Scroller")
            .navigationBarItems(trailing: Button(action: { useList.toggle() }) { Text("Swap") })
        }
    }
}

struct Cell: View {
    var item: String
    var body: some View {
        Text(item)
            .frame(minWidth: 0,maxWidth: .infinity,minHeight: 75)
            .background(Color.green)
    }
}

struct TopInfoPane: View {
    var body: some View {
        Text("TopInfoPane")
            .frame(height: 48)
            .frame(minWidth: 0,maxWidth: .infinity)
            .background(Color.yellow)
    }
}

我尝试将视图上的动画设置为nil并设置.allowsHitTesting(false),但它们没有帮助。我很茫然,因为我真的没想到ScrollView仍然会滚动超出其自己的框架。

解决方法

尝试如下裁剪ScrollView

ScrollView {
    LazyVGrid(columns: gridLayout,alignment: .center,spacing: 8) {
        ForEach(data,id: \.self) { item in
            NavigationLink(destination: Text(item)) {
                Cell(item: item)
            }
        }
    }
}
.contentShape(Rectangle())
.clipped()

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...