[英]How do I toggle a SwiftUI toggle when a view is tapped?
I would like to toggle a Toggle when a view is tapped.我想在点击视图时切换 Toggle。 Right now I have the following code and it works, though the Toggle doesn't animate the transition.
现在我有以下代码并且它可以工作,尽管 Toggle 没有动画转换。 What can I do to fix?
我能做些什么来解决?
import SwiftUI
struct ContentView: View {
@State private var toggle = false
var body: some View {
VStack {
Toggle(isOn: $toggle) {
Text("Hello World")
}
}.onTapGesture {
print("Tapped!")
self.toggle.toggle()
}
}
}
I've also tried to wrap the self.toggle.toggle()
line around a DispatchQueue.main.asynch
, but that didn't change anything.我还尝试将
self.toggle.toggle()
线包裹在DispatchQueue.main.asynch
周围,但这并没有改变任何东西。
Make it with animation as below使用 animation 如下所示
}
// .contentShape(Rectangle()) // << add to make full-area tappable
.onTapGesture {
print("Tapped!")
withAnimation {
self.toggle.toggle()
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.