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())
}
}
當 ViewModifier 的好處就是:可以幫原來的 view 加入新的屬性、State 變數(例如: .nsfw())。 👉 Sundell ⟩ Configuring SwiftUI Views
ViewModifier is a modifier that you apply to a view or another view modifier, producing a different version of the original value.
既然可以直接用 View extension 來改變一個 View,為什麼還需要大費周章弄一個 ViewModifier 呢❓ 👉 why bother using a view modifier?
上面的討論還有網路文章都有提到一點:「ViewModifier 也是 View,可以自訂一些 @State, @Binding 變數,也可設定支援動畫的屬性」,這些特性是 View extension 辦不到的。
Another interesting fact about ViewModifiers is that it conforms to View protocol (#todo:此訊息的資料來源?). It means you can use inside ViewModifiers property wrappers like @State, @Binding, @Environment, @ObservableObject, and @EnvironmentObject. 👉 ViewModifiers in SwiftUI - Swift with Majid
in ViewModifer you can create your own with stored properties, including states and other dynamic properties, also make it animatable, etc. 👉 StackOverflow - @Asperi
ViewBuilder transforms modify views too.
can have @Binding variables.
Can we implement view.if(_:then:) with ViewModifier❓
Animatable Modifiers are Animatable view modifiers.
Why is SwiftUI.ViewModifier a useful concept? 這裡討論了一個有趣的問題:「為什麼需要 ViewModifier?」一般簡單的 view modifier 用 view extension 就可以,複雜一點的、帶有 State 變數的可以另外寫一個 View,為何還需要特別設計一個 ViewModifier?(這裡提出問題,但目前沒人提供答案)
Last updated
Was this helpful?