今回はTabViewの使い方について説明します。非常に簡単なので説明するまでもないかもですが…
環境
- Xcode12.5.1
- 動作はシミュレーターのiPhone12 miniで確認
基本的な使い方
基本的には以下のような実装方法になります。
TabViewのクロージャの中に各ページの内容を書いていき、モディファイアでタブに表示するボタンの内容を実装します。
今回はタブ内の内容をテキストだけにしていますが、もちろん自作のstructを表示することも可能です。
struct ContentView: View {
var body: some View {
TabView{
Text("ページ1")
.tabItem {
Text("ページ1")
}
Text("ページ2")
.tabItem {
Text("ページ2")
}
}
}
}

TabItemのカスタマイズ
lineやfacebookのタブのように、アイコンと文字の両方を表示することも簡単です。
struct ContentView: View {
var body: some View {
TabView{
Text("ホーム")
.tabItem {
Image(systemName: "house")
Text("ホーム")
}
Text("メッセージ")
.tabItem {
Image(systemName: "message")
Text("メッセージ")
}
Text("タイムライン")
.tabItem {
Image(systemName: "clock")
Text("タイムライン")
}
Text("設定")
.tabItem {
Image(systemName: "slider.horizontal.3")
Text("設定")
}
}
}
}

表示できるTabItemは5コまで
以下のようにタブをたくさん追加すると、5つ目以降はMoreと書かれたボタンが表示され省略されます。
struct ContentView: View {
var body: some View {
TabView{
Text("ホーム")
.tabItem {
Image(systemName: "house")
Text("ホーム")
}
Text("メッセージ")
.tabItem {
Image(systemName: "message")
Text("メッセージ")
}
Text("タイムライン")
.tabItem {
Image(systemName: "clock")
Text("タイムライン")
}
Text("設定")
.tabItem {
Image(systemName: "slider.horizontal.3")
Text("設定")
}
Text("ホーム")
.tabItem {
Image(systemName: "house")
Text("ホーム")
}
Text("メッセージ")
.tabItem {
Image(systemName: "message")
Text("メッセージ")
}
Text("タイムライン")
.tabItem {
Image(systemName: "clock")
Text("タイムライン")
}
Text("設定")
.tabItem {
Image(systemName: "slider.horizontal.3")
Text("設定")
}
}
}
}

Moreをタップすると省略されたアイテムがList表示されます。

ちなみに右上のEditを押すと、以下のような画面が表示され、タブに表示するアイテムをカスタマイズできます。

説明に書いてある通り、ドラッグで入れ替えることができます。

コメント