๐ ฟ๏ธViewModifier
SwiftUI โฉ Views โฉ Modifier
View modifiers apply modifications onto a base view and can change any aspect of that view.
็ถ 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
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())
}
}
SwiftUI โฉ
ViewBuilder transforms modify views too.
can have Binding variables.
Can we implement .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