【发布时间】:2020-05-25 23:13:11
【问题描述】:
我正在尝试创建一个“弹出视图”,当绑定值非零时出现。
我有一个 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()
}
}
如何让这个动画进入/退出?
【问题讨论】:
标签: ios animation binding swiftui