LoginSignup
6
5

【SwiftUI】iPhoneでSectionの折りたたみ(.sidebar)を使ってみたら

Last updated at Posted at 2024-02-04

環境

  • Xcode Version 15.2
  • iOS 17.2
  • SwiftUI

問題

従来、Sectionの折りたたみを実装したい場合は以下のように、

OldListExample.swift
import SwiftUI

struct ContentView: View {

    let monbetsuGun = ["湧別町", "遠軽町", "滝上町", "興部町", "西興部村", "雄武町"]
    
    var body: some View {
        List {
            Section {
                ForEach(monbetsuGun, id: \.self) { name in
                    Text(name)
                }
            } header: {
                 Text("紋別郡")
                    .font(.largeTitle)
                    .padding(.top)
            } footer: {
                Text("遠軽町にはでっかい岩がある")
            }
        }
        .listStyle(.sidebar)
    }
}

#Preview {
    ContentView()
}

とSectionに対して.listStyle(.sidebar)をつけるだけで簡単に実装できました。しかし今はこの方法が使えないようになってます。
Simulator Screenshot - iPhone 15 Pro - 2024-02-04 at 14.23.31.png

解決策

代わりに、Appleによってinit(isExpanded:content:header:)が新しく提案されています。これに対して.listStyle(.sidebar)を適応することで折りたたみと展開が実装可能です。

NewListExample.swift
import SwiftUI

struct ContentView: View {

    let monbetsuGun = ["湧別町", "遠軽町", "滝上町", "興部町", "西興部村", "雄武町"]
+ 
+   @State var isExpanded: Bool = false

    var body: some View {
        List {
-           Section {
+           Section(isExpanded: $isExpanded) {
                ForEach(monbetsuGun, id: \.self) { name in
                    Text(name)
                }
            } header: {
                 Text("紋別郡")
                    .font(.largeTitle)
                    .padding(.top)
-           } footer: {
-               Text("遠軽町にはでっかい岩がある")
-           }
        }
        .listStyle(.sidebar)
    }
}

#Preview {
    ContentView()
}

Simulator Screenshot - iPhone 15 Pro - 2024-02-04 at 14.27.20.png
Simulator Screenshot - iPhone 15 Pro - 2024-02-04 at 14.27.22.png

問題点

ワイ「え?!Footerは?!Footerはどこ?!」
Apple「ないで」
スクリーンショット 2024-02-04 14.08.44.png

Footer、お前何やらかしたんや。

どうやったらFooterって実装できるんですかね。わかる方教えてください。

参考

6
5
1

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
6
5