apple/SwiftUI, Combine

SwiftUI ViewModifier

lgvv 2022. 6. 2. 16:03

SwiftUI ViewModifier

 

ViewModifier를 점점 더 많이 활용하고 있는데, 이를 통해 코드를 간결하게 적용할 수 있음.

공식문서를 통해서 공부해보자.

 

 

(공식문서 링크)

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

 

Apple Developer Documentation

 

developer.apple.com

 

 

Overview

특별한 내용은 보다시피 없고 일단 프로토콜이다.

 

공식문서

 

샘플 코드

import SwiftUI

struct ContentView: View {
    
    var body: some View {
        
        VStack(spacing: 50){
            Text("Hello, world!")
                .modifier(MyRoundedText()) // modifier를 활용
            Text("Hello, world!")
                .myRoundedTextStyle()
            Image(systemName: "pencil") // 함수를 활용
                .myRoundedTextStyle()
            Rectangle()
                .frame(width: 100, height: 100)
                .myRoundedTextStyle()
        }
        
    }
}

// 뷰를 꾸며주는 모디파이어
struct MyRoundedText: ViewModifier {
    
    func body(content: Content) -> some View { // content는 내가 받아온 속성에 대한 정보
        content
            .font(.largeTitle)
            .padding()
            .background(Color.init(#colorLiteral(red: 0.9607843161, green: 0.7058823705, blue: 0.200000003, alpha: 1)))
            .cornerRadius(20)
            .padding()
            .overlay(
                RoundedRectangle(cornerRadius: 25).stroke(lineWidth: 10).foregroundColor(.blue)
            )
    }
}

extension View {
    func myRoundedTextStyle() -> some View {
        modifier(MyRoundedText())
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}