4
4

【SwiftUI】SectionにisExpandedが追加され、折りたためるようになった(iOS17)

Posted at

はじめに

iOS17からSectionにisExpandedという引数が追加されました。
これを使用することで、Sectionを開閉することができるようになります。

サンプルアプリ

Simulator Screen Recording - iPhone 15 Pro - 2024-02-10 at 22.07.05.gif

実装

ヘッダーの横に矢印ボタンが出るのはListStyleのsidebarだけでした。
その他のスタイルではisExpanded.toggle()のように値を直接変更しないと開閉できません。

import SwiftUI

struct ContentView: View {
    @State var isExpanded = false
    
    var body: some View {
        List {
            Section(isExpanded: $isExpanded) {
                Text("コンテンツ")
            } header: {
                Text("ヘッダー")
            }
            
            Button {
                withAnimation {
                    isExpanded.toggle()
                }
            } label: {
                Text("開閉")
            }
        }
        .listStyle(.sidebar)
    }
}

おわり

自前で実装するのも簡単そうですが、公式で提供してくれるのは嬉しいですね

公式ドキュメント

4
4
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
4
4