Recent Posts
Recent Comments
| 일 | 월 | 화 | 수 | 목 | 금 | 토 |
|---|---|---|---|---|---|---|
| 1 | 2 | 3 | 4 | 5 | 6 | |
| 7 | 8 | 9 | 10 | 11 | 12 | 13 |
| 14 | 15 | 16 | 17 | 18 | 19 | 20 |
| 21 | 22 | 23 | 24 | 25 | 26 | 27 |
| 28 | 29 | 30 | 31 |
Tags
- NSTextStorageDelegate
- .pbxproj
- Firestore
- 클린 아키텍처
- png
- heic
- spm 에러
- swiftdata
- 무한스크롤
- JPEG
- nidthirdpartylogin
- swift 모듈화
- xcode 엔터 표시
- xcode 공백 표시
- NSTextStorage
- webp
- 타뷸레이션
- JPG
- SwiftUI
- Cocoa Pod
- fetchdescriptor
- 테스트 타겟
- 함께자라기
- 팀 개발을 위한 git
- github 시작하기
- Tuist
- contentalignmentpoint
- 캐러셀
- 코드스쿼드
- TestFlight
Archives
Link
- Today
- Total
Sure, Why not?
@State, @Binding (프로퍼티 래퍼 - 2 ) 본문

@State
뷰가 소유하는 값(Source of Truth) 을 저장하고, 그 값이 바뀌면 해당 뷰의 body를 다시 계산한다.
문서에 따르면,
SwiftUI가 제공하는 저장소 관리 방식과 충돌할 수 있으므로,
멤버와이즈 이니셜라이저에서 state를 설정하지 못하도록 state를 private으로 선언하기를 권장한다.
뷰와 그 하위 뷰에만 국한된 로컬 상태를 저장할 때 사용한다.
항상 기본값으로 초기화되어야 하며, 선언 시점에 값이 필요하다.
struct EditorView: View {
@State private var text: String
init(initialText: String) {
self._text = State(initialValue: initialText)
}
var body: some View {
TextField("edit", text: $text)
}
}
물론 화면 진입 시점의 초기값처럼 외부 데이터로 상태를 시작해야 하는 경우에는,
@State를 직접 주입하기보다는 State(initialValue:)를 통해 초기화 시점에만 값을 반영하고
이후에는 뷰의 로컬 상태로 관리하는 방식을 사용한다.
@Binding
뷰가 소유하지 않은 상태를 읽고, 수정까지 할 수 있도록 연결해주는 프로퍼티 래퍼
struct ParentView: View {
@State private var isPlaying = false
var body: some View {
PlayerToggle(isPlaying: $isPlaying)
}
}
struct PlayerToggle: View {
@Binding var isPlaying: Bool
var body: some View {
Toggle("Play", isOn: $isPlaying)
}
}
- @State → 상태의 소유자 (Source of Truth)
- @Binding → 그 상태를 수정할 수 있는 연결
PlayerToggle는 isPlaying을 소유하지 않지만,
변경은 가능하고, 변경 결과는 자동으로 상위 View에 반영된다.
Reference
State | Apple Developer Documentation
A property wrapper type that can read and write a value managed by SwiftUI.
developer.apple.com
Binding | Apple Developer Documentation
A property wrapper type that can read and write a value owned by a source of truth.
developer.apple.com
'💻' 카테고리의 다른 글
| @propertyWrapper 프로퍼티 래퍼란? - 1 (0) | 2025.12.22 |
|---|---|
| SwiftUI ) @Published는 어떻게 동작하는가 - objectWillChange (1) | 2025.11.27 |
| UITextView에서 한글 스타일 적용 (1) | 2025.10.13 |
| async let vs TaskGroup vs 연속 await (2) | 2025.08.28 |
| Core Bluetooth (3) | 2025.07.21 |