我试图创建一个“弹出视图”,当绑定值非空时出现。
我有一个 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()
}
}
如何使此内容实现动画效果?