0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

[SwiftUI] 背景を描画するViewを作成する

0
Posted at

やりたいこと

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: () -> Contentcontent()が実行された時、Content型の戻り値があるってやつ。()は引数なしって意味
@ViewBuilderは複数のViewをまとめている

//このViewを
Text("A")
Text("B")
Text("C")
//このようにまとめている
TupleView<(Text, Text, Text)>
0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?