
View Modifier가 너무 많아질 경우
코드를 어떻게 정리할까 조금 고민이 있었는데 그에 관한 정리다.
아래는 몇가지 방법론이다.
Extension으로 묶기
extension View {
func commonCardStyle() -> some View {
self
.padding()
.background(Color.white)
.cornerRadius(10)
.shadow(radius: 5)
}
}
// 사용
struct ContentView: View {
var body: some View {
Text("Hello")
.commonCardStyle()
}
}
ViewBuilder로 컴포넌트화
struct CardView<Content: View>: View {
let content: Content
init(@ViewBuilder content: () -> Content) {
self.content = content()
}
var body: some View {
content
.padding()
.background(Color.white)
.cornerRadius(10)
}
}
// 사용
CardView {
Text("Hello")
}
Group으로 modifier 그룹화
Text("Hello")
.Group {
if isHighlighted {
$0.foregroundColor(.red)
.bold()
} else {
$0.foregroundColor(.gray)
}
}
.padding()
기능별로 modifier를 별도 메서드로 분리
struct ContentView: View {
var body: some View {
Text("Hello")
.applyTextStyle()
.applyCardStyle()
}
private func applyTextStyle<T: View>(_ view: T) -> some View {
view
.font(.title)
.foregroundColor(.blue)
}
private func applyCardStyle<T: View>(_ view: T) -> some View {
view
.padding()
.background(Color.white)
}
}