Skip to content

Instantly share code, notes, and snippets.

@benigumocom
Last active August 23, 2024 02:31
Show Gist options
  • Save benigumocom/db70399fa8e57ad10356fd7fc5d31e50 to your computer and use it in GitHub Desktop.
Save benigumocom/db70399fa8e57ad10356fd7fc5d31e50 to your computer and use it in GitHub Desktop.
【SwiftUI】Apple 公式サンプルで Animation と Transition はどのように使われているか 👉 https://android.benigumo.com/20240822/swiftui-animation-transition/
import SwiftUI
// 【SwiftUI】アニメーションの書き方
// https://zenn.dev/maochanz/articles/b3f2b0dcf949c5
//【SwiftUI】トランジションの書き方
// https://zenn.dev/maochanz/articles/0bcd4bfaa43a0d
struct AnimatedMessage: View {
var text: String
@State private var showIcon = false
@State private var showText = false
var body: some View {
HStack(spacing: 0) {
if showIcon { // *
Image(systemName: "heart.fill")
.foregroundStyle(.red)
.font(.title)
.padding()
.transition(.scale(scale:0.25).combined(with: .opacity)) // *
}
if showText { // *
Text(text)
.padding(.trailing, 24)
.transition(.scale(scale:0.5).combined(with: .opacity)) // *
}
}
.clipShape(.capsule)
.background(
.regularMaterial.shadow(.drop(radius: 16)),
in: .capsule
)
.frame(height: 50)
.onAppear {
Task {
withAnimation(.spring(duration: 0.5, bounce: 0.5)) { // *
showIcon = true
}
try await Task.sleep(for: .seconds(1))
withAnimation { // *
showText = true
}
try await Task.sleep(for: .seconds(3))
withAnimation { // *
showText = false
}
try await Task.sleep(for: .seconds(1))
withAnimation { // *
showIcon = false
}
}
}
}
}
//【SwiftUI】View の 強制再描画
// https://android.benigumo.com/20240324/force-redraw/
private struct RefreshPreview: View {
var text: String
@State private var id = false
var body: some View {
AnimatedMessage(text: text)
.id(id)
Button("Refresh") {
id.toggle()
}
.buttonStyle(.borderedProminent)
}
}
#Preview("once") {
AnimatedMessage(text: "Hello, world !")
.padding()
.frame(maxWidth: .infinity)
}
#Preview("refresh") {
RefreshPreview(text: "Hello, world !!!")
.padding()
.frame(maxWidth: .infinity)
}
@benigumocom
Copy link
Author

sc 2024-08-22 at 21 49 39

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment