HIT해
[Swift/TCA] binding 변수 처리하기 ( TCA 1.12.1 ) 본문
https://github.com/pointfreeco/swift-composable-architecture
GitHub - pointfreeco/swift-composable-architecture: A library for building applications in a consistent and understandable way,
A library for building applications in a consistent and understandable way, with composition, testing, and ergonomics in mind. - pointfreeco/swift-composable-architecture
github.com
TCA 를 활용한 Binding 처리는 두가지가 존재한다.
- BindingReducer 선언하기
- @Bindable Store 선언 후 action을 binding처리
각 구현 방법을 구체적으로 알아보자
1. BindingReducer 선언하기
우선 Action을 BindableAction 프로토콜에 맞추어 정의를 해주어야한다.
enum Action: BindableAction {
case binding( BindingAction < State >)
}
그리고 리듀서 선언부에 BindingReducer()를 선언해준다.
BindingReducer ()
Reduce { state, action in
switch action {
case .binding(\.message):
print ("toDolMessage" , state.message)
return .none
case .binding(\.selectedFace) :
print("changed Face : ", state.selectedFace)
return .none
case .binding( _ ):
return .none
.binding(\.바인딩하려는 state 값) 을 넣어주면 바인딩 변수로 사용가능하다.
사용할때는 이런식으로 사용해주면 된다.
@State var store: StoreOf<HomeFeature>
...
CustomTextField(text: $store.message)
2. @Bindable Store 선언 후 action을 binding처리
해당 방식은 모든 변수를 Binding가능한 변수로 만드는 것이 아니라 action을 통해 값이 변경될때마다 state값을 변경해주는 방법이다.
변수선언
@ObservableState
struct State : Equatable {
var userName = ""
}
리듀서 선언
별도의 BindingReducer 선언 없이 액션에 값의 변경을 바로 넣어준다.
case let .userNameChanged(name):
state.userName = name
return .none
뷰에서 사용할때
@State가 아닌 @Bindable로 선언해줘야한다.
@Bindable var store : StoreOf<MyPageFeature>
...
TextField("", text: $store.userName.sending(\.userNameChanged))
어떤 방식을 사용해도 차이는 없지만 가독성 측면으로 보았을때 2번 구현 방식이 더 좋았다.
그럼 20000!
'Swift > Swift 개발 노트' 카테고리의 다른 글
[Swift/SwiftUI] 높이가 동적으로 변하는 Text 입력란 만들기 (0) | 2024.09.30 |
---|---|
[Swift/SwiftUI] 줄바꿈 단위 글자단위 <-> 어절단위 (0) | 2024.09.26 |
[Swift/TCA] warning: data race detected: @MainActor function at ComposableArchitecture/Binding+Observation.swift:164 was not called on the main thread 에러 해결하기 (0) | 2024.09.24 |
[Swift/UIImage] 이미지 잘라내기 cropping (0) | 2024.09.23 |
[Swift/SceneKit] 3D 모델 캡쳐하기 (0) | 2024.09.23 |