0
2

More than 3 years have passed since last update.

TabViewで選択時のタブを画像毎置き換える方法

Last updated at Posted at 2021-09-01

やったことなど

今回はタブボタンを選択した時の変化を「アイコン」に対してやってみようと思いました。
参考ページでは「SF Symbol」のフォントを変化させる方法が掲載されています。
とある案件で選択時のタブボタンを画像毎変える必要があったため、なんとか手を加えて試してみました。
構成やソースはほぼ参考サイトを引用しています。

コード

引用したソースから「systemName:」を削除して少しImageの名前を変えた程度でなんとかうまくいきました。

struct ContentView: View {

    // タブの種類
    enum Tab {
        case circle
        case square
    }

    // 選択中のタブ
    @State private var selection: Tab = .circle

    var body: some View {
        TabView (selection: $selection) {
            Text("円の画面")
                .tabItem {
                    Image(selection == .circle ?
                            "circle-shadow" : // 選択時
                            "circle") // 非選択時
                        .imageScale(.large)
                    Text("円")
                }
                .tag(Tab.circle) // タブの種類を指定
            Text("四角の画面")
                .tabItem {
                    Image(selection == .square ?
                            "square-shadow" : // 選択時
                            "square") // 非選択時
                        .imageScale(.large)
                    Text("四角")
                }
                .tag(Tab.square) // タブの種類を指定
        }
    }
}

結果

円のタブ選択時のタブ画像の変化

Simulator Screen Shot - iPod touch (7th generation) - 2021-09-01 at 15.09.33.png

四角のタブ選択時のタブ画像の変化

Simulator Screen Shot - iPod touch (7th generation) - 2021-09-01 at 15.09.36.png

思ったこと

「.tag(Tab.circle)」の記載が重要でした。
このtagがないと思い通りにタブボタンが変化してくれませんでした。
あとは、selectionの記法で選択中のタブ情報を保持できるのはお手軽で楽だなと思いました。
参考サイトに感謝を申し上げます。

参考

[SwiftUI]TabViewで選択時のアイコンを変更する

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