やりたいこと
Viewに毎回背景を描画するコードを書きたくないので、背景用のViewファイルを作成する
//これを
struct ContentView: View {
var body: some View {
ZStack{
Color.appBackground
.ignoresSafeArea()
Text("Hello, World!")
}
}
}
//こうしたい
struct ContentView: View {
var body: some View {
AppBackgroundView {
Text("Hello, world!")
}
}
}
AppBackgroundView()じゃダメなのか
正直これでもやりたいことは達成できる。ただコードが汚くなると思う(?)
背景用のためだけに用意されたZStackが邪魔すぎますよね。
あと、Modifier追加した時全てのZStackを修正しないといけないという作業が発生する
struct ContentView: View {
var body: some View {
ZStack{
AppBackgroundView()
VStack{
Text("Hello, World!")
Text("Hello, World!")
}
}
}
}
全体のコード
//AppBackgroundView.swift
import SwiftUI
struct AppBackgroundView<Content: View>: View {
let content: Content
init(@ViewBuilder content: () -> Content){
self.content = content()
}
var body: some View {
ZStack{
Color.appBackground
.ignoresSafeArea()
content
}
}
}
#Preview {
AppBackgroundView{
}
}
// ContentView.swift
import SwiftUI
struct ContentView: View {
var body: some View {
AppBackgroundView{
Text("Hello, world!")
}
}
}
#Preview {
ContentView()
}
struct AppBackgroundView<Content: View>: View
struct ContentView: View {
var body: some View {
AppBackgroundView{
//ここのViewを渡せるようにしている
}
}
}
init(@ViewBuilder content: () -> Content)
Viewを作るための関数
content: () -> Contentはcontent()が実行された時、Content型の戻り値があるってやつ。()は引数なしって意味
@ViewBuilderは複数のViewをまとめている
//このViewを
Text("A")
Text("B")
Text("C")
//このようにまとめている
TupleView<(Text, Text, Text)>