admin管理员组文章数量:1122846
I am not updating any value that causes a UI change—just updating a random value—and it triggers this weird animation in macOS SwiftUI.
import SwiftUI
struct CanvasView: View {
@State private var size: CGSize = CGSize()
var body: some View {
Color.yellow
.frame(width: 500.0, height: 300.0)
.animation(Animation.linear(duration: 2.2), value: size)
.onAppear {
size = CGSize(width: 500.0, height: 300.0)
}
}
}
I am not updating any value that causes a UI change—just updating a random value—and it triggers this weird animation in macOS SwiftUI.
import SwiftUI
struct CanvasView: View {
@State private var size: CGSize = CGSize()
var body: some View {
Color.yellow
.frame(width: 500.0, height: 300.0)
.animation(Animation.linear(duration: 2.2), value: size)
.onAppear {
size = CGSize(width: 500.0, height: 300.0)
}
}
}
Share
Improve this question
asked Nov 22, 2024 at 23:42
swiftPunkswiftPunk
1
0
1 Answer
Reset to default 1When onAppear
is called, SwiftUI has not positioned the views to where they should be. The line in onAppear
changes size
from (0, 0) to (500, 300). This triggers an animation.
By the time SwiftUI determines what should be animated, the view has now been positioned to the correct place. Since the position changed, the position is animated, from wherever random position SwiftUI initially put it, to the correct position.
This can be fixed in a lot of ways:
add a
geometryGroup
:Color.yellow.geometryGroup()
adding
.animation(nil, value: size)
before.animation(Animation.linear(duration: 2.2), value: size)
. This effectively restricts the "scope" of the animation to only the view modifiers between these two.animation
modifiers.animation(_:body:)
does something similar.Delaying
size = CGSize(width: 500.0, height: 300.0)
using aTask { ... }
orDispatchQueue.main.async { ... }
.
See also these very similar problems:
- SwiftUI unexpected animations when toggling animations In .onAppear (using a GeometryReader's size)
- ToolbarItem is included in the animation but shouldn't
本文标签: Why is there a weirdunexpected animation on onAppear in macOS SwiftUIStack Overflow
版权声明:本文标题:Why is there a weird, unexpected animation on onAppear in macOS SwiftUI? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1736300310a1930768.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论