🅿️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
Was this helpful?