我有一个重置按钮,要求首先确认。我想设置isSure为 false 是用户触摸组件外部。
我可以从 Button 组件执行此操作吗?
这是我的按钮:
struct ResetButton: View {
var onConfirmPress: () -> Void;
@State private var isSure: Bool = false;
var body: some View {
Button(action: {
if (self.isSure) {
self.onConfirmPress();
self.isSure.toggle();
} else {
self.isSure.toggle();
}
}) {
Text(self.isSure ? "Are you sure?" : "Reset")
}
}
}
Run Code Online (Sandbox Code Playgroud)
wor*_*dog 13
这是一种方法:
struct ContentView: View {
var onConfirmPress: () -> Void
@State private var isSure: Bool = false
var body: some View {
GeometryReader { geometry in
ZStack {
// a transparent rectangle under everything
Rectangle()
.frame(width: geometry.size.width, height: geometry.size.height)
.opacity(0.001) // <--- important
.layoutPriority(-1)
.onTapGesture {
self.isSure = false
print("---> onTapGesture self.isSure : \(self.isSure)")
}
Button(action: {
if (self.isSure) {
self.onConfirmPress()
}
self.isSure.toggle()
}) {
Text(self.isSure ? "Are you sure?" : "Reset").padding(10).border(Color.black)
}
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
基本上,我们有一些视图,并且我们希望点击其背景来执行某些操作 - 这意味着我们想要添加一个巨大的背景来注册点击。请注意,.background仅提供主视图的大小,但始终可以设置显式的不同大小!如果你知道你的尺寸那就太好了,否则 UIScreen 可以工作......
这很hacky,但似乎有效!
extension View {
@ViewBuilder
private func onTapBackgroundContent(enabled: Bool, _ action: @escaping () -> Void) -> some View {
if enabled {
Color.clear
.frame(width: UIScreen.main.bounds.width * 2, height: UIScreen.main.bounds.height * 2)
.contentShape(Rectangle())
.onTapGesture(perform: action)
}
}
func onTapBackground(enabled: Bool, _ action: @escaping () -> Void) -> some View {
background(
onTapBackgroundContent(enabled: enabled, action)
)
}
}
Run Code Online (Sandbox Code Playgroud)
用法:
SomeView()
.onTapBackground(enabled: isShowingAlert) {
isShowingAlert = false
}
Run Code Online (Sandbox Code Playgroud)
这可以很容易地改变以进行绑定:
func onTapBackground(set value: Binding<Bool>) -> some View {
background(
onTapBackgroundContent(enabled: value.wrappedValue) { value.wrappedValue = false }
)
}
// later...
SomeView()
.onTapBackground(set: $isShowingAlert)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4527 次 |
| 最近记录: |