はじめに
@BindingStateの使い方を記録しておきます
完成
実装
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めっちゃむずいです