Skip to content

SwiftUI_ui_component

kobayashiharuto edited this page Aug 21, 2021 · 1 revision

コンポーネントに分けよう

大きなアプリになってくると、コードが長くなり読みづらくなってしまいます。
そのうえ、以下のような同じものの繰り返しは冗長的ですね。

struct ContentView: View {

    var body: some View {
        VStack {
            Text("りんご")
                .font(.title)
                .padding(10)
                .foregroundcolor(.red)
         
            Text("バナナ")
                .font(.title)
                .padding(10)
                .foregroundcolor(.red)
         
            Text("メロン")
                .font(.title)
                .padding(10)
                .foregroundcolor(.red)
        }
    }
}

こんな時は、以下のようにテキストの部分だけ分けてしまいましょう。
イニシャライザで、果物を受け取るようにします。

struct FruitText: View {
    let fruit: String

    init(sruit: String) {
        self.fruit = fruit 
    }

    var body: some View {
        Text(fruit)
            .font(.title)
            .padding(10)
            .foregroundcolor(.red)
    }
}

これで、さっきのコードは以下のように書き変えれます。

struct ContentView: View {

    var body: some View {
        VStack {
            FruitText(fruit: "りんご")
            FruitText(fruit: "バナナ")
            FruitText(fruit: "メロン")
        }
    }
}

とても綺麗になりましたね!
このように、使いまわせるように分けた View をコンポーネントと言います。
コードが読みやすくなるうえ、修正があってもまとめて適用できるので非常に便利です!

Clone this wiki locally