1
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?

More than 1 year has passed since last update.

【Swift】TCAでのアラートの表示方法

Posted at

はじめに

以前、「【SwiftUI】TCAでアラートを実装する」という記事を書きましたが、
TCA独自のアラート表示方法があったのでそちらの方法を記録しておきます

実装

import SwiftUI
import ComposableArchitecture

struct ContentView: View {
    @ObservedObject private var viewStore: ViewStoreOf<Feature>
    
    let store: StoreOf<Feature>
    
    init(store: StoreOf<Feature>) {
        self.store = store
        self.viewStore = ViewStore(store, observe: { $0 })
    }

    var body: some View {
        Button {
            viewStore.send(.buttonTapped)
        } label: {
            Text("テスト")
        }
+       .alert(store: store.scope(state: \.$alert, action: Feature.Action.alert))
    }
}
import ComposableArchitecture

struct Feature: Reducer {
    struct State: Equatable {
+       @PresentationState var alert: AlertState<Action.Alert>?
    }

    enum Action: Equatable {
        case buttonTapped
+       case alert(PresentationAction<Alert>)
        
+       public enum Alert: Equatable {
+           /* アラートのボタンにアクションを追加したい場合はここにActionを追加 */
+       }
    }
    
    func reduce(into state: inout State, action: Action) -> Effect<Action> {
        switch action {
        case .buttonTapped:
+           state.alert = .init(title: .init("アラートです"))
            return .none
+       case .alert:
+           return .none
        }
    }
}

おわり

TCAは独自実装が多いので学習コストが高いです、、、

1
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
1
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?