Swift UI withAnimation(.linear) 上的持续时间参数
Duration parameter on Swift UI withAnimation(.linear)
我正在研究 Swift UI 的线性动画技术,并注意到,与我的预期相反,增加持续时间似乎并没有使动画发生得更慢。这是故意的吗?如果是这样,我该如何制作更慢的动画?
示例代码:
struct ButtonView: View {
@State var show: Bool = false
var body: some View {
ZStack{
if show {
withAnimation(.linear(duration: 50)) {
CollapsibleView()
}
}
}
Button(action: { show = !show }) {
Text("Press Me")
}
}
}
struct CollapsibleView: View {
var body: some View {
VStack {
Text("Text 1")
Text("Text 2")
Text("Text 3")
}
}
}
@main
struct app: App {
var body: some Scene {
WindowGroup {
ButtonView()
}
}
}
尝试更改持续时间参数,看看您是否能注意到较慢的动画。我达到了 5000(我假设这是以秒为单位?)并且它仍然以看似相同的速度进行动画处理。
您已将 withAnimation
放置在视图层次结构中。您真正想要它的地方是 Button
的操作:
struct ButtonView: View {
@State var show: Bool = false
var body: some View {
ZStack{
if show {
CollapsibleView()
}
}
Button(action: {
withAnimation(.linear(duration: 10)) {
show.toggle()
}
}) {
Text("Press Me")
}
}
}
或者,您可以在 ZStack
上使用 .animation
:
struct ButtonView: View {
@State var show: Bool = false
var body: some View {
ZStack{
if show {
CollapsibleView()
}
}
.animation(.linear(duration: 10), value: show)
Button(action: {
show.toggle()
}) {
Text("Press Me")
}
}
}
我正在研究 Swift UI 的线性动画技术,并注意到,与我的预期相反,增加持续时间似乎并没有使动画发生得更慢。这是故意的吗?如果是这样,我该如何制作更慢的动画?
示例代码:
struct ButtonView: View {
@State var show: Bool = false
var body: some View {
ZStack{
if show {
withAnimation(.linear(duration: 50)) {
CollapsibleView()
}
}
}
Button(action: { show = !show }) {
Text("Press Me")
}
}
}
struct CollapsibleView: View {
var body: some View {
VStack {
Text("Text 1")
Text("Text 2")
Text("Text 3")
}
}
}
@main
struct app: App {
var body: some Scene {
WindowGroup {
ButtonView()
}
}
}
尝试更改持续时间参数,看看您是否能注意到较慢的动画。我达到了 5000(我假设这是以秒为单位?)并且它仍然以看似相同的速度进行动画处理。
您已将 withAnimation
放置在视图层次结构中。您真正想要它的地方是 Button
的操作:
struct ButtonView: View {
@State var show: Bool = false
var body: some View {
ZStack{
if show {
CollapsibleView()
}
}
Button(action: {
withAnimation(.linear(duration: 10)) {
show.toggle()
}
}) {
Text("Press Me")
}
}
}
或者,您可以在 ZStack
上使用 .animation
:
struct ButtonView: View {
@State var show: Bool = false
var body: some View {
ZStack{
if show {
CollapsibleView()
}
}
.animation(.linear(duration: 10), value: show)
Button(action: {
show.toggle()
}) {
Text("Press Me")
}
}
}