gpt4 book ai didi

ios - SwiftUI 动画不会在绑定(bind)更新时发生

转载 作者:行者123 更新时间:2023-12-01 21:48:00 28 4
gpt4 key购买 nike

我正在尝试创建一个当绑定(bind)值非零时出现的“弹出 View ”。

enter image description here

我有一个 PopupCard 类,它在 Content 和一些 Value 上通用......

struct PopupCard<Content: View, Value>: View {
@Binding private var data: Value?
private let content: (Value) -> Content

init(data: Binding<Value?>, @ViewBuilder content: @escaping (Value) -> Content) {
self._data = data
self.content = content
}

var body: some View {
Group {
if data != nil {
HStack {
self.content(self.data!)
.padding()
Spacer()
}
.frame(width: UIScreen.main.bounds.width - 40)
.background(
Rectangle()
.fill(Color.yellow)
.shadow(color: Color.black.opacity(0.2), radius: 5, y: 0)
)
.offset(y: self.data == nil ? -100 : 0)
.animation(.default)
}
}
}
}

我还在 View 上创建了以下扩展......

extension View {
func popup<Content: View, Value>(data: Binding<Value?>, @ViewBuilder content: @escaping (Value) -> Content) -> some View {
return ZStack {
self
VStack {
Spacer()
PopupCard(data: data, content: content)
}
}
}
}

这一切都很好,除了动画。卡片按预期出现和消失,但没有动画。这在以下预览中进行了演示……

struct PopupCard_Previews: PreviewProvider {
struct PreviewView: View {
@State var name: String? = "Hello"
var body: some View {
TabView {
Button("Toggle", action: {
self.name = self.name == nil ? "Hello" : nil

})
.popup(data: $name) { string in
Text(string)
}
}
}
}

static var previews: some View {
PreviewView()
}
}

我如何让这个动画进/出?

最佳答案

这是固定变体(如果我正确理解了意图)。使用 Xcode 11.4/iOS 13.4 测试

demo

struct PopupCard<Content: View, Value>: View {
@Binding private var data: Value?
private let content: (Value) -> Content

init(data: Binding<Value?>, @ViewBuilder content: @escaping (Value) -> Content) {
self._data = data
self.content = content
}

var body: some View {
Group {
HStack {
if data != nil {
self.content(self.data!).padding()
} else {
Text("")
}
Spacer()
}
.frame(width: UIScreen.main.bounds.width - 40)
.background(
Rectangle()
.fill(Color.yellow)
.shadow(color: Color.black.opacity(0.2), radius: 5, y: 0)
)
.compositingGroup()
.offset(y: self.data == nil ? 100 : 0)
.animation(.default)
}
}
}

关于ios - SwiftUI 动画不会在绑定(bind)更新时发生,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62004963/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com