今回は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")
}
}
}
}
![](https://shuhey-hashimoto.com/wp-content/uploads/2021/09/Simulator-Screen-Shot-iPhone-12-mini-2021-09-25-at-17.28.13.png)
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("設定")
}
}
}
}
![](https://shuhey-hashimoto.com/wp-content/uploads/2021/09/Simulator-Screen-Shot-iPhone-12-mini-2021-09-25-at-18.37.06.png)
表示できる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("設定")
}
}
}
}
![](https://shuhey-hashimoto.com/wp-content/uploads/2021/09/Simulator-Screen-Shot-iPhone-12-mini-2021-09-25-at-18.43.21.png)
Moreをタップすると省略されたアイテムがList表示されます。
![](https://shuhey-hashimoto.com/wp-content/uploads/2021/09/Simulator-Screen-Shot-iPhone-12-mini-2021-09-25-at-18.42.38.png)
ちなみに右上のEditを押すと、以下のような画面が表示され、タブに表示するアイテムをカスタマイズできます。
![](https://shuhey-hashimoto.com/wp-content/uploads/2021/09/Simulator-Screen-Shot-iPhone-12-mini-2021-09-25-at-18.48.49.png)
説明に書いてある通り、ドラッグで入れ替えることができます。
![](https://shuhey-hashimoto.com/wp-content/uploads/2021/09/Simulator-Screen-Shot-iPhone-12-mini-2021-09-25-at-18.46.42-2.png)
コメント