Search
Duplicate

Conditional modifier - 조건에 따라 다른 효과 뷰에 적용하기

태그
조건에 따라서 다른 모디파이어를 적용시키고 싶을 때가 있다
이를 Conditional Modifier 라고하며 이의 구현방법에 대해서 알아보자

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 - 삼항연산자

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

extension View { @ViewBuilder func `if`<Content: View>(_ condition: Bool, transform: (Self) -> Content) -> some View { if condition { transform(self) } else { self } } }
Swift
복사
뷰 프로토콜을 확장하여 새로운 모디파이어를 정의한다.
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
복사
조건에 부합하면 뷰에 모디파이어를 적용하고 그렇지 않다면 자기자신을 리턴하는 if 메서드를 생성하였다.