swift - SwiftUI 中的动画状态变化
问题描述
我目前正在玩 SwiftUI。在 SwiftUI 中,可以为状态更改设置动画,例如:
struct Foo: View {
@State private var show = false
var body: some View {
VStack {
if show {
Text("Foo")
}
Button(action: {
withAnimation {
self.show.toggle()
}
}) {
Text(show ? "Hide" : "Show")
}
}
}
}
但是,如果我有一个 TextField:
struct Foo: View {
@State private var text = ""
var body: some View {
VStack {
TextField($text, placeholder: Text("Foo")) {
print("editing ended")
}
if !text.isEmpty {
Button(action: {}) {
Text("Done")
}
}
}
}
}
我无法找到为这种更改设置动画的方法,因为 TextField 更改了 State 属性,而无需调用 withAnimation()。
是否有可能使这种变化动画化?
解决方案
只需添加动画修饰符来包装您的按钮
var body: some View {
VStack {
TextField($text, placeholder: Text("Foo")) {
print("editing ended")
}
// if !text.isEmpty {
Button(action: {}) {
Text("Done")
}
.background(text.isEmpty ? Color.red : Color.yellow )
//.animation(.basic(duration: 1))
.animation(Animation.default.speed(1))
}
}
}
推荐阅读
- linux - Linux - 查找文件夹更改时间是否大于 2 小时
- php - 带有 3 个实例的 AWS Elastic Beanstalk 上的 Laravel 验证错误为空
- java - 使用 json-simple (JAVA) 删除 JSON 文件的部分
- java - 我无法完美地将 Java 转换为 Kotlin
- python - 模拟 ldap 调用总是返回 True
- python - 从heroku服务器中的python脚本运行节点子进程
- html - 动态选择的选定标签不起作用
- java - 无法从类型中对非静态方法 getX() 进行静态引用
- sql - 如果有名字和姓氏超过一个字符,则从表中查找大写名字和姓氏
- python - 从python中的url列表中提取数据时,多处理不起作用