SwiftUI Property Wrappers - @Binding

sanghoon Ahn·2023년 2월 12일
0

SwiftUI

목록 보기
2/5

@Binding

읽고 쓰기가 가능하며 다른 view에서 property를 전달받을 때 사용합니다.

바인딩을 받은 view는 바인딩된 속성을 읽을 수 있고, 외부에 의한 변경도 응답할 수 있습니다.

또한 write access도 가지고 있어 property를 변경할 수 도 있습니다.

@Binding을 업데이트하면 @Binding을 전달한 view의 해당 property가 업데이트된다는 것을 의미합니다.

data가 변함에 따라 변경되는 view와 data를 저장하는 property를 연결할 때 사용합니다.

binding은 data를 직접 저장하는 대신에 source of truth에 연결합니다.

SwiftUI 문서를 보다보면.. source of truth가 계속 나오는데
요게 무엇일까 궁금해서 찾아보았는데

정보 시스템 설계 및 이론중 하나라고 합니다.

자세한 내용은 아래 링크를 참고해주세요!
https://en.wikipedia.org/wiki/Single_source_of_truth
https://developer.apple.com/videos/play/wwdc2020/10119/

우선 간단하게 source of truth는 단어 그대로 이해하면 편한것 같습니다.

struct PlayButton: View {
    @Binding var isPlaying: Bool

    var body: some View {
        Button(isPlaying ? "Pause" : "Play") {
            isPlaying.toggle()
        }
    }
}

예를 들어 토글되는 button의 상태를 button과 binding하고 싶다면, @Binding property wrapper를 아래와 같이 사용할 수 있습니다.

struct StateView: View {
    @State private var intValue = 0
    
    var body: some View {
        VStack {
            Text("intValue equals \(intValue)")
            
            BindingView(intValue: $intValue)
        }
    }
}

struct BindingView: View {
    @Binding var intValue: Int
    
    var body: some View {
        Button("Increment") {
            intValue += 1
        }
    }
}

위의 예시는 BindingView가 init시 source of truth로 @State인 intValue를 전달받고, BindingView는 넘겨받은 intValue를 @Binding property로 연결합니다.

이후 user의 Button tap action에 의해 @Binding property가 변화하는 예시입니다.

@State로 wrapping 된 intValue를 BindingView에 projecteValue를 사용하여 전달하였습니다.

@State property의 예상 값은 직접 바인딩이 아닌 바인딩을 통해 @State 속성을 수정할 수 있도록 BindingView에 전달할 수 있는 Binding입니다.

SwiftUI는 내부적으로 discard된 view의 @Binding을 유지하지 않습니다. @Binding property는 항상 외부에서 주입받기 때문입니다.

@State proerty는 리렌더링시 유지되는것과는 차이점이라고 할 수 있겠네요.

그렇다면 @Binding property가 변경되면 source of truth(@State)가 변경되고 다시 view가 리렌더링 되게 되는걸까?
https://developer.apple.com/videos/play/wwdc2021/10022

@Binding을 사용하는 경우는

  • parent view에서 전달받은 property의 read & write가 필요한 경우
  • value type(struct, enum)을 wrapping할 때 (reference type을 wrapping 하여도 문제없지만 일반적이지 않습니다)

참고자료

profile
hello, iOS

4개의 댓글

comment-user-thumbnail
2025년 2월 19일

Whether you're a seasoned musician or a casual gamer looking for a unique experience, Sprunki offers an immersive platform to express your musical creativity.

답글 달기
comment-user-thumbnail
2025년 4월 23일

Tired of opening too many tabs to access different writing and research tool websites? We understand your frustration, so Humanize AI provides One-stop Writing Assistant: Humanize AI Text(Get 100% Human Score);ChatPDF;Essay Writer;AI Cover Letter;Grammar Checker…
Save yourself time, energy, and frustration with our range of helpful products.
Humanize AI: https://humanizeai.tools/humanize-ai

답글 달기
comment-user-thumbnail
2025년 4월 23일

Deepora AI is an AI model integration platform that allows free access to cutting-edge AI large models such as DeepSeek, ChatGPT,Grok and so on.
Deepora AI: https://deepora.ai/

답글 달기
comment-user-thumbnail
2025년 4월 23일

VidText AI is a free AI-driven tool that transcribe video & audio to text quickly and accurately.Support 100+Languages, Generate Mind map, 15 Hour Uploads, over 99% Accuracy.Perfect for meetings, lectures, interviews, and content creators,helping you effortlessly transcribe video and audio to accurate and readable text and mindmap.
VidText AI: https://vidtext.ai/

답글 달기