LoginSignup
10
6

More than 3 years have passed since last update.

SwiftUIのTabbedViewで遊んでみる

Last updated at Posted at 2019-06-07

SwiftUIをさわり始めて数日ですが、今までのやり方で「どうやってやるの?」的なことが多くあると思いますが、今回扱うTabbarも色々変わっっているので軽くまとめます。

あと、Viewの背景色変更する方法を暫定ですがいい感じにできたのでそこも紹介します。

※スクショは自粛で〜

First Code

Tabbarでの構成でプロジェクトを作成するとこんな感じにContentViewを作成してくれます。

まずはこれだけを見ていきましょう😃

struct ContentView : View {
    @State private var selection = 0

    var body: some View {
        TabbedView(selection: $selection){
            Text("First View")
                .font(.title)
                .tabItemLabel(Image("first"))
                .tag(0)
            Text("Second View")
                .font(.title)
                .tabItemLabel(Image("second"))
                .tag(1)
        }
    }
}

SetTabItem

タブバーのアイテムを設定してあげています
画像なりテキストなり

func tabItemLabel<V>(V) -> _ModifiedContent<TabbedView<SelectionValue, Content>, _TraitWritingModifier<AnyView?>>

Sets the tab item to be used for this content.

Configuring Switch View

要調査ですがタグを振ってあげないとうまく切り替わってくれないです

func tag<V>(V) -> _AutoResultView<TabbedView<SelectionValue, Content>>

Viewの切り替え

ContentView.swift

        TabbedView(selection: $selection) {
            FirstView()
                .tabItemLabel(Image("first"))
                .tag(0)

            SecondView()
                .tabItemLabel(Image("second"))
                .tag(1)
            }
            .onAppear { print(onAppear) }


FirstView

struct FirstView : View {
    var body: some View {
            Text("First")
    }
}

SecondView

struct SecondView : View {
    var body: some View {
            Text(Second")
    }
}

Append self view background color

View全体に背景色を追加する方法ですね
正しいやり方か分からんけど、

ZStackを使うのはわかったけどSpacerの挙動がイマイチ理解できない、、

    var body: some View {

        ZStack {
            Spacer()
                .position(.zero)
            Text("First")
                .color(Color.white)
            }.background(Color.red)
            .edgesIgnoringSafeArea(.all)
    }

タブバーで表示されるViewを画面全体に表示

.edgesIgnoringSafeArea(.all)だとタブバー見えなくなちゃったので上だけで


struct ContentView : View {
    @State private var selection = 0

    var body: some View {
        TabbedView(selection: $selection) {
            FirstView()
                .tabItemLabel(Image("first"))
                .tag(0)

            SecondView()
                .tabItemLabel(Image("second"))
                .tag(1)
            }
            .onAppear { print("onAppear") }
            .edgesIgnoringSafeArea(.top)
    }
}
10
6
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
10
6