LoginSignup
1
2

More than 1 year has passed since last update.

【SwiftUI】Viewの中でなるべくif文を使いたくない

Posted at

はじめに

View内にif文があると美しくないので、View内でif文を使う時用のViewを用意してみました。

実装

PlaceholderView
import SwiftUI

struct PlaceholderView<Content: View, Placeholder: View>: View {
    var `if`: Bool

    @ViewBuilder var content: () -> Content

    @ViewBuilder var placeholder: () -> Placeholder

    var body: some View {
        if `if` {
            content()
        } else {
            placeholder()
        }
    }
}

使い方

ContentView
import SwiftUI

struct ContentView: View {
    @State var isLoading: Bool = false
    var body: some View {
        VStack(spacing: 50) {
            PlaceholderView(if: isLoading) {
                Text("コンテンツ")
            } placeholder: {
                Text("プレイスホルダー")
            }
            
            Button {
                isLoading.toggle()
            } label: {
                Text("切り替え")
            }
        }
    }
}

動画

Simulator Screen Recording - iPhone 14 Pro - 2023-04-14 at 22.20.46.gif

おわり

最近、TCAを勉強してるのですが、ReducerProtocolが追加される前の記事が多くて辛いです笑

1
2
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
1
2