🪢@Binding 사용하기

sanghee·2021년 8월 19일
0

🚩iOS

목록 보기
9/18
post-thumbnail

Binding

Apple Developer Documentation - Binding

A property wrapper type that can read and write a value owned by a source of truth.

속성을 감싸는 타입으로 데이터가 모인 곳이 가진 값을 읽거나 쓸 수 있다.

🪢@Binding

@Binding을 사용하여 데이터를 저장하는 속성과 데이터를 보여주고 바꾸는 뷰 사이를 양방향으로 연결한다. 바인딩은 데이터가 모인 곳과 연결한다. 직접 데이터를 저장하는 것을 제외하고 가능하다.

PlayButton

예를 들어, 토글 버튼은 부모의 뷰의 속성을 Binding으로 감쌀 수 있다.

struct PlayButton: View {
    @Binding var isPlaying: Bool

    var body: some View {
        Button(action: {
            self.isPlaying.toggle()
        }) {
            Image(systemName: isPlaying ? "pause.circle" : "play.circle")
        }
    }
}

PlayerView

부모의 뷰는 @State를 써서 isPlaying 속성을 저장한다. PlayButton을 생성할 때 $를 앞에 붙여 isPlaying을 넘긴다.

struct PlayerView: View {
    var episode: Episode
    @State private var isPlaying: Bool = false

    var body: some View {
        VStack {
            PlayButton(isPlaying: $isPlaying)
        }
    }
}

FirstView의 show → SecondView → ThirdView 전달하여 사용

부모 뷰로부터 show를 전달받고 전달받는 예제이다. init에 show의 앞에 _를 붙이는 것을 확인할 수 있다. Swift의 Property Wrappers의 일부이다.

  • self.$show는 self._show.projectValue와 같으며 Binding이다. 값을 변경할 필요가 있을 때 자식뷰에게 이 형태로 넘겨준다.
  • self._show는 Binding이다.
  • self.show는 self._show.wrappedValue이며 불린값이다. 이 값은 ThirdView에서 값을 표현할 때 사용한다.
struct FirstView: View {
    @State private var show = false
		
    var body: some View {
        NavigationLink(
            destination: SecondView(show: $show)
        )
    }
}

struct SecondView: View {
    @Binding var show: Bool

    var body: some View {
        NavigationLink(
            destination: ThirdView(show: $show)
        )
    }
}
struct ThirdView: View {
    @Binding var show: Bool
    
    init(show: Binding<Bool>) {
        self._show = show
    }

    var body: some View {
        Button(
            action: { show.toggle() },
            label: { show ? Text("Show") : Text("Hide") }
        )
    }
}
profile
👩‍💻

0개의 댓글