图像主体中的 swiftui 三元运算符不播放动画和过渡
swiftui ternary operator in image body doesn`t play animation and transition
我试过使用三元迭代器来简化动态图片处理代码,但是这个方法在SwiftUI中好像没有成功。你能解释一下为什么吗?
以下代码按预期执行动画和过渡。
import SwiftUI
struct SwiftUIView: View {
@State private var onOff = true
var image: String
var nextPhoto: String
var body: some View {
VStack {
Button(action: {
withAnimation(.spring(dampingFraction: 2.825) ) {
self.onOff.toggle()
}
}) {
Text("Button")
}
if onOff {
Image(image)
.transition(.scale)
.animation (.default)
} else {
Image(nextPhoto)
.transition(.scale)
.animation (.default)
}
}
}
}
struct SwiftUIView_Previews: PreviewProvider {
static var previews: some View {
SwiftUIView(image: "photo", nextPhoto: "photo_next")
}
}
但是,当我使用三元运算符时,动画停止工作。如何用三元简化这段代码?有什么想法吗?
struct SwiftUIView: View {
@State private var onOff = true
var image: String
var nextPhoto: String
var body: some View {
VStack {
Button(action: {
withAnimation(.spring(dampingFraction: 2.825) ) {
self.onOff.toggle()
}
}) {
Text("Button")
}
Image(onOff ? image : nextPhoto)
.transition(.scale)
.animation (.default)
}
}
}
我也尝试了以下选项,但也失败了。
var image = onOff ? self.image : nextPhoto
Image(image)
.transition(.scale)
.animation (.default)
我不能post动画视频,因为我的声望低,所以我会post问题的gif是这样的:
Result of first code
Result of second code
试试这个,虽然我不确定,
var image = onOff ? self.image : nextPhoto
Image(image)
.transition(.scale)
.animation (.default)
我试过使用三元迭代器来简化动态图片处理代码,但是这个方法在SwiftUI中好像没有成功。你能解释一下为什么吗?
以下代码按预期执行动画和过渡。
import SwiftUI
struct SwiftUIView: View {
@State private var onOff = true
var image: String
var nextPhoto: String
var body: some View {
VStack {
Button(action: {
withAnimation(.spring(dampingFraction: 2.825) ) {
self.onOff.toggle()
}
}) {
Text("Button")
}
if onOff {
Image(image)
.transition(.scale)
.animation (.default)
} else {
Image(nextPhoto)
.transition(.scale)
.animation (.default)
}
}
}
}
struct SwiftUIView_Previews: PreviewProvider {
static var previews: some View {
SwiftUIView(image: "photo", nextPhoto: "photo_next")
}
}
但是,当我使用三元运算符时,动画停止工作。如何用三元简化这段代码?有什么想法吗?
struct SwiftUIView: View {
@State private var onOff = true
var image: String
var nextPhoto: String
var body: some View {
VStack {
Button(action: {
withAnimation(.spring(dampingFraction: 2.825) ) {
self.onOff.toggle()
}
}) {
Text("Button")
}
Image(onOff ? image : nextPhoto)
.transition(.scale)
.animation (.default)
}
}
}
我也尝试了以下选项,但也失败了。
var image = onOff ? self.image : nextPhoto
Image(image)
.transition(.scale)
.animation (.default)
我不能post动画视频,因为我的声望低,所以我会post问题的gif是这样的: Result of first code Result of second code
试试这个,虽然我不确定,
var image = onOff ? self.image : nextPhoto
Image(image)
.transition(.scale)
.animation (.default)