ios - 更新 Binding 时未发生 SwiftUI 动画
问题描述
我正在尝试创建一个在绑定值非零时出现的“弹出视图”。
我有一个PopupCard
通用的类,Content
还有一些Value
……</p>
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
……上创建了以下扩展程序</p>
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)
}
}
}
}
这一切都很好,除了动画。卡片按预期出现和消失,但没有动画。这在下面的预览中得到了演示……</p>
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 测试
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)
}
}
}
推荐阅读
- excel - Excel 公式,根据所需的最低利润 (GP%) 计算最大权重
- c - c 中的连接字符:“char”类型的参数与“const char*”类型的参数不兼容
- python - KeyError: word not in words,当我使用 gensim.Word2Vec 处理中文标记时
- c++ - 在 C++ 中将我的类分成不同的头文件
- firebase - Dialogflow 从 Firebase 实时数据库中检索数据
- mysql - 选择具有非空值列的记录
- blackjack - 二十一点缺失算法
- javascript - 如何为复制到剪贴板制作多重选择器或多重ID
- android - 扫描每个像素以获取 RGB 值
- google-chrome - Chrome 版本 66:阻止当前来源接收跨站点文档