0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

SwiftUIでトーストの出し方🍞

Posted at

トースト通知の使い方(ToastView)

✅ 目的

音声認識の結果やユーザーアクションに対して、一時的なメッセージを画面上部に表示するためのトースト通知。


📦 ToastView の定義(すでにプロジェクトに追加済み)

struct ToastView: View {
    let message: String

    var body: some View {
        Text(message)
            .font(.subheadline)
            .foregroundColor(.white)
            .padding(.horizontal, 16)
            .padding(.vertical, 10)
            .background(Color.black.opacity(0.8))
            .cornerRadius(8)
            .padding(.top, 50)
            .transition(.move(edge: .top).combined(with: .opacity))
            .animation(.easeInOut(duration: 0.3), value: message)
    }
}

🧪 呼び出しサンプル

以下は、ボタンを押したときに「コピーしました」というトーストを2秒表示する例です。

@State private var showToast = false

Button("コピー") {
    UIPasteboard.general.string = "コピーされたテキスト"
    showToast = true
    DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
        showToast = false
    }
}
.overlay(
    Group {
        if showToast {
            ToastView(message: "コピーしました")
        }
    },
    alignment: .top
)

🧼 補足

  • 複数のトーストを出す場合は message を動的に変えて制御できます。
  • 表示中に新しいトーストを出す際は withAnimation を使うとよりスムーズです。

📘 ContentView.swift での具体例

以下は、音声認識結果を旧APIで取得し、クリップボードにコピーされた後にトーストを表示する実装例です。

@State private var showToast = false
@StateObject private var vm = TranscriptionViewModel()

var body: some View {
    VStack {
        Button("旧APIで認識してコピー") {
            LegacySpeechTester().testEmbeddedFileWithLegacyAPI { result in
                DispatchQueue.main.async {
                    vm.transcript = result ?? "認識結果がありませんでした"
                    if let result = result {
                        UIPasteboard.general.string = result
                        showToast = true
                        DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
                            showToast = false
                        }
                    }
                }
            }
        }

        ScrollView {
            Text(vm.transcript)
                .padding()
        }
    }
    .overlay(
        Group {
            if showToast {
                ToastView(message: "コピーしました")
            }
        },
        alignment: .top
    )
}

このように .overlay() を使ってトーストを簡単に追加できます。

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?