swiftui - 条件子视图的 SwiftUI 转换
问题描述
我正在尝试理解和试验 swiftUI 视图转换,并且可以使用一些洞察力来了解为什么以下内容不能按我预期的方式工作:
struct ContentView: View {
@State private var showOverlay: Bool = false
var body: some View {
ZStack {
VStack {
Button(action: {
withAnimation(.easeInOut) {
self.showOverlay = true
}
}) {
Text("Hello, World!")
}
}
.zIndex(0)
.animation(nil)
.blur(radius: showOverlay ? 3 : 0)
if showOverlay {
HStack {
Button(action: {
withAnimation(.easeInOut) {
self.showOverlay = false
}
}) {
Text("Close")
}
.frame(width: 80, height: 80)
.background(Color.red)
.transition(.move(edge: .top))
Button(action: {
withAnimation(.easeInOut) {
self.showOverlay = false
}
}) {
Text("Close")
}
.frame(width: 80, height: 80)
.background(Color.red)
.transition(.move(edge: .bottom))
}
.zIndex(1.0)
}
}
}
有两个按钮的条件 HStack。当@State 参数showOverlay
改变时,它在一个withAnimation
块内完成。单个按钮上的转换不受支持。
如果我删除 HStack,并将 zIndex(1) 放在每个按钮上,则会发生删除转换,但不会发生插入转换。
我希望两个按钮在它们的组添加到视图时以指定的方式转换。
问题:为什么包装在 HStack 中会导致内部转换被忽略?为什么边缘过渡只在 1 个方向上起作用?
解决方案
为了获得两种不同的动画,您可以将条件逻辑拉近按钮,即在HStack
:
HStack {
if showOverlay {
Button(action: {
withAnimation(.easeInOut) {
self.showOverlay = false
}
}) {
Text("Close")
}
.frame(width: 80, height: 80)
.background(Color.red)
.transition(.move(edge: .top))
Button(action: {
withAnimation(.easeInOut) {
self.showOverlay = false
}
}) {
Text("Close")
}
.frame(width: 80, height: 80)
.background(Color.red)
.transition(.move(edge: .bottom))
}
}
.zIndex(1.0)
这会给你留下一个空的HStack
when showOverlay == false
,但这应该不是什么大问题,至少在这个例子中是这样。
推荐阅读
- c# - 执行 SSIS 包结果失败 DTSError is the executable is not specified
- python - 我在使用 python-bs4 抓取请求时不断收到不同的错误消息
- sql - 在 SQL 中计算转化率
- typescript - TypeScript:接口取决于(递归)属性的类型
- sql - Postgresql group by 显示所有元素甚至为空
- angular - 如何允许用户在另一个选项卡中打开页面而不必再次登录
- xcode - Xcode 12 更新中断 Pod 和产品
- c# - Log all handles exception
- css - 有条件地将文本列表分成两列
- sql - 使用 MAX 查找给定其他属性的最新时间