【发布时间】:2021-04-27 20:07:27
【问题描述】:
我想要一个按钮,按下时会变为“确认”。在第二次按下时,它执行操作。到目前为止很简单。
我还希望每当显示按钮的“确认”版本时,与任何其他视图的任何交互都会将该按钮重置为其原始状态。这可能是触摸背景、按下另一个按钮、转到另一个选项卡等。
我的尝试是这样的:
struct ContentView: View {
@State private var confirmShowing = false
var body: some View {
ZStack {
// Tappable background just to remove the confirmation
Color(.systemBackground)
.edgesIgnoringSafeArea(.all)
.onTapGesture {
withAnimation {
confirmShowing = false
}
}
VStack {
// Button which needs confirmation
Button(action: {
if confirmShowing {
print("Executing")
}
withAnimation {
confirmShowing.toggle()
}
}) {
Text( confirmShowing ? "Confirm" : "Do something" )
}
.padding()
.background( Rectangle().foregroundColor( Color(.secondarySystemBackground) ) )
.padding()
// Completely different button which also should first reset confirmation
Button("Do something else") {
withAnimation {
confirmShowing = false
}
// do some other stuff
}
.padding()
.background( Rectangle().foregroundColor( Color(.secondarySystemBackground) ) )
.padding()
}
}
}
}
它适用于这个非常简单的示例,但它不可扩展。如果我有 50 个视图,我将不得不为每个视图添加一些内容来控制这个按钮。
有没有更好的方法?我很高兴使用 UIViewRepresentable/UIViewControllerRepresentable。
UIKit 应该有这个功能吧?我经常在其他应用程序和 iOS 中看到它。
【问题讨论】: