ToolbarItem の配置

ToolbarItem の placement パラメータで、ボタンの配置位置を細かく制御できます。各配置オプションの特徴と使い分けを解説します。

ナビゲーションバーの配置

.toolbar {
    ToolbarItem(placement: .topBarLeading) {
        Button("左") { }
    }
    
    ToolbarItem(placement: .topBarTrailing) {
        Button("右") { }
    }
    
    ToolbarItem(placement: .principal) {
        Text("中央")
    }
}
配置位置用途
.topBarLeading左側戻るボタンの代わり、キャンセル
.topBarTrailing右側追加、編集、設定
.principal中央カスタムタイトル、セグメント

ボトムバーの配置

.toolbar {
    ToolbarItem(placement: .bottomBar) {
        HStack {
            Button { } label: { Image(systemName: "trash") }
            Spacer()
            Text("3項目選択中")
            Spacer()
            Button { } label: { Image(systemName: "square.and.arrow.up") }
        }
    }
}

自動配置

placement を省略すると、プラットフォームに応じた適切な位置に自動配置されます。

.toolbar {
    Button("ボタン") { }  // 自動的に .topBarTrailing に配置されることが多い
}

標準的なアクション用の配置

特定の用途に最適化された配置オプションもあります。

.toolbar {
    ToolbarItem(placement: .confirmationAction) {
        Button("保存") { }
    }
    
    ToolbarItem(placement: .cancellationAction) {
        Button("キャンセル") { }
    }
    
    ToolbarItem(placement: .destructiveAction) {
        Button("削除") { }
    }
}
.confirmationAction

確定アクション(保存、完了など)。通常は右側に配置される。

.cancellationAction

キャンセルアクション。通常は左側に配置される。

.destructiveAction

破壊的アクション(削除など)。プラットフォームによって適切な位置に配置される。

.primaryAction

メインのアクション。目立つ位置に配置される。

プラットフォームによる違い

同じ placement でも、iOS、macOS、watchOS で配置位置が異なることがあります。

.toolbar {
    // iOS: 右上
    // macOS: ツールバー領域
    ToolbarItem(placement: .primaryAction) {
        Button("アクション") { }
    }
}

principal でカスタムタイトル

.principal を使うと、ナビゲーションバーの中央にカスタムビューを配置できます。

.toolbar {
    ToolbarItem(placement: .principal) {
        VStack {
            Text("メインタイトル")
                .font(.headline)
            Text("サブタイトル")
                .font(.caption)
                .foregroundColor(.gray)
        }
    }
}

セグメントコントロールを配置する例:

struct ContentView: View {
    @State private var selection = 0
    
    var body: some View {
        NavigationStack {
            Text("コンテンツ")
                .toolbar {
                    ToolbarItem(placement: .principal) {
                        Picker("表示", selection: $selection) {
                            Text("リスト").tag(0)
                            Text("グリッド").tag(1)
                        }
                        .pickerStyle(.segmented)
                        .frame(width: 200)
                    }
                }
        }
    }
}
semantic placement

.confirmationAction などの意味的な配置。プラットフォームに最適化される。

explicit placement

.topBarTrailing などの明示的な配置。位置を正確に制御したい場合に使用。

配置を適切に選択することで、各プラットフォームの UI ガイドラインに沿った自然な操作感を実現できます。