Last active
August 23, 2024 02:31
-
-
Save benigumocom/db70399fa8e57ad10356fd7fc5d31e50 to your computer and use it in GitHub Desktop.
【SwiftUI】Apple 公式サンプルで Animation と Transition はどのように使われているか 👉 https://android.benigumo.com/20240822/swiftui-animation-transition/
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
} | |
Author
benigumocom
commented
Aug 22, 2024
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment