๐Ÿ…ฟ๏ธViewModifier

โ•ฑ๐Ÿšง under construction

SwiftUI โŸฉ views โŸฉ modifier โŸฉ ViewModifier (protocol)

๐Ÿšง

// ViewModifier (protocol)
protocol ViewModifier {
    // input type of body()
    typealias Content            
    // output type of body()
    associatedtype Body: View    
    // โญ๏ธ only requirement
    func body(content: Self.Content) -> Self.Body
}

protocol ViewModifier {
    typealias Content            // input type of body()
    associatedtype Body: View    // output type of body()
    // โญ๏ธ only requirement
   func body(content: Self.Content) -> Self.Body
}

็ญ”๏ผš

  • Content ๆ˜ฏ body() ็š„่ผธๅ…ฅๅž‹ๅˆฅ๏ผˆ_ViewModifier_Content<Self>๏ผ‰๏ผŒไฝฟ็”จ่€…็„กๆณ•ๆ”น่ฎŠ๏ผŒๅชๆ˜ฏ็‚บไบ†ไฝฟ็”จ่€…ๆ–นไพฟ่€Œ่จญ็š„ typealiasใ€‚

  • Body ๆ˜ฏ body() ็š„่ผธๅ‡บๅž‹ๅˆฅ๏ผŒๅฏไปฅ็”ฑไฝฟ็”จ่€…่‡ช็”ฑๆŒ‡ๅฎš๏ผˆไฝ†็”ฑ compiler ่‡ชๅ‹•่พจ่ญ˜๏ผ‰๏ผŒๆ‰€ไปฅๆ˜ฏๅ€‹ associatedtype๏ผŒไนŸๅ› ๆญค ViewModifier ่ฎŠๆˆไธ€ๅ€‹ generic protocolใ€‚

๐Ÿ’พ ๆจกๆฟ

import SwiftUI

// (internal) view modifier
struct MyViewModifier: ViewModifier {
    
    // โญ๏ธ new states
    @State private var blur = true              
    
    // body
    func body(content: Content) -> some View {
        // โญ๏ธ handle input `content`
        content
            .blur(radius: blur ? 20 : 0)
            .clipped()
            .onTapGesture { 
                withAnimation {
                    self.blur.toggle()
                }
            }
    }
}

// โญ๏ธ public helper
extension View {
    public func myModifier() -> some View { 
        modifier(MyViewModifier()) 
    }
}

Last updated