0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

SwiftUIでToolbarTitleMenuの表示を動的に切り替える

0
Posted at

ToolbarTitleMenu
↑このNavigationTitleの右横にある矢印がToolbarTitleMenu

条件を満たした場合、NavigationTitleの横にメニューボタンが表示される。ここからタイトルの編集などが可能だ。
単に削除するだけなら条件から外すだけで良いが、編集可能な場面でのみ編集させたい。

表示される条件は、NavigationTitleの引数にBindingが指定されている、かつ.navigationBarTitleDisplayMode(.inline)の場合。
ToolbarItem(placement: .title)で上書きした場合も同様の挙動となる。

NavigationTitleを拡張し、引数に渡す値を定数化することで、動的な削除を可能にする。

extension View {
    @ViewBuilder
    func navigationTitle(_ title:Binding<String>, menuHide:Bool) -> some View {
        if menuHide {
            self
                .navigationTitle(title.wrappedValue)
        } else {
            self
                .navigationTitle(title)
        }
    }
}

通常はこれで動的切り替えが可能。

.navigationTitle($title,menu:flag)

もしToolbarTitleMenuの中身を追加・変更しているなら、.toolbarモディファイア内でToolbarTitleMenuToolbarContentを削除する必要がある。

.toolbar {
    if flag {
        ToolbarTitleMenu {
            RenameButton()
        }
    }
}

ToolbarTitleMenuは初期値でシステムが推測したボタンを提供するため、これだけではToolbarTitleMenu自体を非表示にすることはできない。
中身を空にした場合、内部的に表示されるMenuは消せるが、Buttonは残り続ける。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?