0
1

More than 1 year has passed since last update.

はじめに

@BindingStateの使い方を記録しておきます

完成

画面収録-2023-09-15-19.59.47.gif

実装

Reducer

import Foundation
import ComposableArchitecture

public struct SampleReducer: Reducer {
    public init() {}

    // MARK: - State
    public struct State: Equatable {
+       @BindingState var text = "" // @BindingStateを付与
        
        public init() {}
    }

    // MARK: - Action
+   public enum Action: BindableAction, Equatable { // `BindableAction`に準拠させる
+       case binding(BindingAction<State>)
    }

    // MARK: - Reducer
    public var body: some ReducerOf<Self> {
+       BindingReducer() // ここが重要
        
        Reduce { state, action in
            switch action {
+           case .binding(\.$text):  // ここにtextの変更が流れてくる
+               print("変更:", state.text)
+               return .none
+           case .binding: // ここはその他の`binding`が流れてくる(今回はなし)
+               return .none
            }
        }
    }
}

View

import SwiftUI

struct ContentView: View {
    @ObservedObject private var viewStore: ViewStoreOf<SampleReducer>
    
    let store: StoreOf<SampleReducer>
    
    init(store: StoreOf<SampleReducer>) {
        self.store = store
        self.viewStore = ViewStore(store, observe: { $0 })
    }
    
    var body: some View {
        VStack {
            TextField("search", text: viewStore.$text) // 使う時は`$`を付ける
                .textFieldStyle(.roundedBorder)
        }
        .padding(.horizontal, 20)
    }
}

おわり

TCAめっちゃむずいです

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