Notice
Recent Posts
Recent Comments
Link
๊ด€๋ฆฌ ๋ฉ”๋‰ด

lgvv98

[SwiftUI] ViewModifier ๋ณธ๋ฌธ

apple/๐Ÿš SwiftUI & Combine

[SwiftUI] ViewModifier

๐Ÿฅ• ์บ๋Ÿฟ๋งจ 2022. 6. 2. 16:03

ViewModifier

โœ… ๊ณต์‹๋ฌธ์„œ

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

 

Apple Developer Documentation

 

developer.apple.com

 

โœ… ๊ณต์„๋ฌธ์„œ์˜ ์ผ๋ถ€

๊ณต์‹๋ฌธ์„œ

 

โœ… ์ด๋ฅผ ํ†ตํ•ด์„œ ์ค‘๋ณต๋˜๋Š” ์ฝ”๋“œ๋ฅผ ์‰ฝ๊ฒŒ ์ค„์ผ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

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()
    }
}

 

๊ฒฐ๊ณผ๋ฌผ

 

Comments