안녕하세요 iOS 개발자 루크입니다
오늘은 조건에 따라서 View 를 변경하고자할 때,
사용 가능한 solution 몇가지를 알아보겠습니다.
If else statement
가장 간단한 방법이나, 코드의 중복이 발생
struct ContentView: View {
    @State private var shouldBeRed: Bool = true
    var body: some View {
        if shouldBeRed {
            Text("Hello, world!")
                .foregroundColor(.red)
        } else {
            Text("Hello, world!")
                .foregroundColor(.blue)
        }
    }
}
Swift
복사
Ternary operator : 삼항 연산자 활용
조건에 따라 다르게 modifier 를 사용하고자할 때 사용
struct ContentView: View {
    @State private var shouldBeRed: Bool = true
    var body: some View {
        Text("Hello, world!")
            .foregroundColor(shouldBeRed ? .red : .blue)
    }
}
Swift
복사
Adding a View extension
조건에 따라 modifier 의 적용 여부를 결정할 때 사용
extension View {
    @ViewBuilder func `if`<Content: View>(_ condition: Bool, transform: (Self) -> Content) -> some View {
        if condition {
            transform(self)
        } else {
            self
        }
    }
}
Swift
복사
State 변수를 사용해 View 변경
struct ContentView: View {
    @State private var shouldAddShadow: Bool = true
    var body: some View {
        Text("Hello, world!")
            .if(shouldAddShadow) { view in
                view.shadow(color: .black, radius: 10, x: 0.0, y: 0.0)
            }
    }
}
Swift
복사
감사합니다.