6
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【SwiftUI】Toolbarを関数に切り出す

Posted at

はじめに

Toolbarを関数に切り出す時にsome Viewだとできなかったのでやり方を調べました
他のViewとは違うやり方だったので記録しておきます。

実装

基本形

import SwiftUI

struct ContentView: View {
    var body: some View {
        NavigationStack {
            List {
                // cell
            }
            .toolbar(content: toolbar)
        }
    }

    private func toolbar() -> some ToolbarContent {
        ToolbarItem(placement: .navigationBarLeading) {
            Button {
                // action
            } label: {
                Text("キャンセル")
            }
        }
    }
}

複数ボタンを配置したい

import SwiftUI

struct ContentView: View {
    var body: some View {
        NavigationStack {
            List {
                // cell
            }
            .toolbar(content: toolbar)
        }
    }

    @ToolbarContentBuilder
    private func toolbar() -> some ToolbarContent {
        ToolbarItem(placement: .navigationBarLeading) {
            Button {
                // action
            } label: {
                Text("キャンセル")
            }
        }

        ToolbarItem(placement: .navigationBarTrailing) {
            Button {
                // action
            } label: {
                Text("保存")
            }
        }
    }
}

if文で分岐させたい

import SwiftUI

struct ContentView: View {
    @State private var isCancel = true
    
    var body: some View {
        NavigationStack {
            List {
                // cell
            }
            .toolbar(content: toolbar)
        }
    }

    @ToolbarContentBuilder
    private func toolbar() -> some ToolbarContent {
        if isCancel {
            ToolbarItem(placement: .navigationBarLeading) {
                Button {
                    // action
                } label: {
                    Text("キャンセル")
                }
            }
        } else {
            ToolbarItem(placement: .navigationBarLeading) {
                Button {
                    // action
                } label: {
                    Text("戻る")
                }
            }
        }
    }
}

おわり

これは知りませんでした

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?