티스토리 뷰

SwiftUI

SwiftUI) @ViewBuilder

행복하고 싶은 사람 2022. 10. 7. 15:08

Closure에서 View를 구성하는 custom parameter attribute

 

-> Closure에서 View를 구성한다! 

 

 

1. @ViewBuilder - Parameter

우리가 View를 구성할 때 HStack, VStack, ZStack를 자주 씁니다. HStack의 생성자는 이렇게 생겼습니다.

@inlinable public init(alignment: VerticalAlignment = .center,
                       spacing: CGFloat? = nil,
                       @ViewBuilder content: () -> Content)

보면 마지막 파라미터에 @ViewBuilder가 달려있습니다.

이렇게 @ViewBuilder를 사용해서 View를 custom해서 Child View를 만들어 줄 수 있는것!

import SwiftUI
import Foundation

struct CustomHStack<Content>: View where Content: View {
    let content: () -> Content
    let color: Color
    
    init(color: Color = .clear,
         @ViewBuilder content: @escaping () -> Content) {
        self.color = color
        self.content = content
    }
    
    var body: some View {
        HStack {
            content()
        }
        .background(color)
    }
}

생성자가 필요없다면

struct CustomHStack<Content>: View where Content: View {

  @ViewBuilder let content: Content

  var body: some View {
      HStack {
          content
      }.background(Color.purple)
  }
}

이렇게 content를 @ViewBuilder로 mark해서 사용해도 됩니다.

2. @ViewBuilder - computed property, Method

@ViewBuilder는 파라미터 앞에 붙을 수도 있지만 computed Property나 method앞에도 붙을 수 있습니다.

struct ContentView: View {
    var body: some View {
        HStack {
            Text("Hello")
            Text("My")
            Text("name")
            Text("is")
            Text("____")
        }
    }
}

이 코드에서 HStack 내부가 지저분해보여서 Computed Property로 빼보려합니다

struct ContentView: View {
    var body: some View {
       introduce
    }
		var introduce: some View {
		Text("Hello")
        Text("My")
        Text("name")
        Text("is")
        Text("____")
		}		
}

만약 Computed Property에서 View 여러개를 가지게 하면 컴파일 에러가 뜸 그런데 body로 하면 안뜸

왜?

body 프로퍼티는 @ViewBuilder로 선언되어 있기 때문이다~

그러므로 다른 프로퍼티나 메서드에서는 @ViewBuilder를 명시적으로 넣어줘야함!

struct ContentView: View {
    var body: some View {
       introduce
    }
		@ViewBuilder
		var introduce: some View {
		Text("Hello")
        Text("My")
        Text("name")
        Text("is")
        Text("____")
		}		
}

이렇게!

 

참고: https://zeddios.tistory.com/1324

 

SwiftUI ) ViewBuilder

안녕하세요 :) Zedd입니다. 오늘은 ViewBuilder에 대해 공부! # ViewBuilder 정의 : Closure에서 View를 구성하는 custom parameter attribute 뭔소린지 모르겠지만 "Closure에서 (Child) View를 구성한다"만 알..

zeddios.tistory.com

https://developer.apple.com/documentation/swiftui/viewbuilder

'SwiftUI' 카테고리의 다른 글

SwiftUI) About TabView  (0) 2022.10.31
SwiftUI) About UIViewRepresentable  (0) 2022.10.27
SwiftUI) About ViewModifier  (0) 2022.09.28
SwiftUI) About ButtonStyle  (0) 2022.08.23
SwiftUI) @ObservedObject, @StateObject, @EnvironmentObject 정리  (0) 2022.08.01
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/05   »
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
글 보관함