SwiftUI ViewModifier vs ViewBuilder
https://vinsol.com/blog/2020/07/02/understanding-swiftuis-viewmodifiers-and-viewbuilders/
摘要:
ViewModifier:
- 大多數 SwiftUI 的 View function 都是 View Modifier。Ex: font(), foregroundColor()
- view Modifier 是 SwiftUI 中最常用來 modify View 的方式,用來產生客製化 Custom container View
- Example:
structMyViewModifier:ViewModifier{privateletctaThemeColor =Color.bluefuncbody(content:Content) -> someView{content.foregroundColor(.white).padding().background(ctaThemeColor).clipShape(Capsule())}使用:}
Text("Hello World") .modifier(MyViewModifier())
- 一直需要重複使用到的Base View,創造一個自己的 View Container,類似 VStack(), HStack()
- Example:
structMyContainerView<Content:View>:View{letcontent:Contentinit(@ViewBuildercontent: () ->Content) {self.content = content()}varbody: someView{ZStack{Color.yellow.edgesIgnoringSafeArea(.all)HStack{Spacer()VStack{Text("DemoApp").foregroundColor(.purple).font(.system(size: 15, weight: .bold)).padding(.trailing, 15)Spacer()}}content}}使用:}structDemoAppView:View{varbody: someView{MyContainerView{Text("I ❤️ SwiftUI")// The main content}}}
留言