LoginSignup
1
1

More than 1 year has passed since last update.

SwiftUI 2.0:toolbar()とToolbarItemよりnavigationBarItems()のほうがセーフ?

Posted at

SwiftUI 2.0: Use navigationBarItems() instead of toolbar() with ToolbarItem? (English)

My problem

残念ながら、SwiftUIはナビゲーションバーのスタイルを直接公開しません。

SwiftUIアプリケーションのナビゲーションバーの外観をカスタマイズするために、UINavigationBar.appearance()メソッドを使用してinit()メソッドでナビゲーションバーの色を設定するというトリックを使用しました ...

これは、アプリのナビゲーションバーをカスタマイズする最良の方法ではありませんが、情報を探していたときにインターネットで見つけた方法はでした。これにより、以前にfileImporterのスタイルを設定しようとしたときにも問題が発生しました!

SwiftUI
structMyAppView: View {
    init() { // Color Settings
        UINavigationBar.appearance().tintColor = UIColor(named: "MyNavBarColor")
        // ...
    }
    //...
}

問題は、toolbar(content:)を使用してナビゲーションバーをカスタマイズしたときに始まりました:

SwiftUI
    // ...
    .toolbar(content: {
        ToolbarItem(placement: .navigationBarLeading) {
            /// The screen title
            Text("My Title")
                .foregroundColor(Color("MyForegroundColor"))
                .font(.system(size: 30))
        }
        ToolbarItem(placement: .navigationBarTrailing) {
            Button(action: {
                showNewAchievementForm.toggle()
            }) {
                Image(systemName: showNewAchievementForm ? "multiply.circle.fill" : "plus.circle.fill")
                    .font(.system(size: 30, weight: .light))
                    .foregroundColor(Color("MyForegroundColor"))
            }
            .disabled(!canAddNewAchievement())
        }
    })

UINavigationBar.appearance().tintColorinit()で設定されている場合、ToolbarItemの前景色は無視されました。

My solution

アプリケーション画面の1つは、代わりにnavigationBarItems(leading:trailing:)を使用していました。

SwiftUI
    // ...
    .navigationBarItems(
        leading:
            /// The screen title
            Text("My Title")
                .foregroundColor(Color("MyForegroundColor"))
                .font(.system(size: 30)),
        trailing:
            Button(action: {
                showNewAchievementForm.toggle()
            }) {
               Image(systemName: showNewAchievementForm ? "multiply.circle.fill" : "plus.circle.fill")
                   .font(.system(size: 30))
                   .foregroundColor(Color("MyForegroundColor"))
            }
            .disabled(!canAddNewAchievement())
    )

しかし、現在は非推奨となり、navigationBarLeadingまたはnavigationBarTrailing配置を備えたtoolbar(content:)が推奨されています。

未来

SwiftUI3.0はすぐ発表されるはずので、カスタマイズは確実に改善されます。

もう少し待って見ましょう

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