我使用 ZStack 编写了以下代码。这是使用 ZStack 实现的底部工作表。
我想让上层View变灰,阻止下层View的按钮响应。但下层View的按钮有反应。
这使得无法再现模态底部片材运动。
当上层视图退出时,如何防止下层视图响应?
代码:
import SwiftUI
struct ContentView: View {
@State private var isShow = false
var body: some View {
ZStack {
Button(
"Show Sheet",
action: {
withAnimation {
self.isShow.toggle()
}
}
)
.zIndex(0)
BottomSheet(
isShow: self.$isShow,
content: {
VStack {
Text("A")
Text("B")
Text("C")
}
.frame(
maxWidth: .infinity
)
.background(Color(.yellow))
}
)
.zIndex(1)
}
}
}
struct ScrimView: View {
var body: some View {
VStack {}.frame(
maxWidth: .infinity,
maxHeight: .infinity,
alignment: .bottom
)
.background(
Color(.gray)
)
}
}
struct BottomSheet<Content: View>: View {
private let content: () -> Content
@Binding var isShow: Bool
init(
isShow: Binding<Bool>,
content: @escaping () -> Content
) {
self._isShow = isShow
self.content = content
}
var body: some View {
ZStack(alignment: .bottom) {
ScrimView().zIndex(
0
)
.opacity(
self.isShow ? 0.5 : 0
)
VStack {
Button(
"X",
action: {
withAnimation {
self.isShow = false
}
}
)
self.content()
}
.zIndex(1)
.background(Color(.white))
.cornerRadius(10)
.offset(x: 0, y: self.isShow ? 0 : 500)
}
}
}
Run Code Online (Sandbox Code Playgroud)
主要的:
import SwiftUI
@main
struct FooApp: App {
var body: some Scene {
WindowGroup {
ContentView()
}
}
}
Run Code Online (Sandbox Code Playgroud)
我想在各种视图中使用底部工作表。因此,在这种情况下仅关闭按钮是没有意义的。
有2种方法:
视觉上没有变化,只是忽略按下按钮。
Button("Show Sheet") {
withAnimation {
self.isShow.toggle()
}
)
.allowsHitTesting(!isShow)
Run Code Online (Sandbox Code Playgroud)
在视觉上禁用该按钮(看起来是灰色的)。
Button("Show Sheet") {
withAnimation {
self.isShow.toggle()
}
)
.disabled(isShow)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
342 次 |
| 最近记录: |