SwiftUI 2.0:toolbar()とToolbarItemよりnavigationBarItems()のほうがセーフ?(日本語)
My problem
Unfortunately SwiftUI does not expose navigation styling directly.
To customize my SwiftUI application navigation bar appearance, I used the trick of setting the navigation bar colors in the init()
method using the UINavigationBar.appearance()
method ...
Which is not the best way of Customizing Your App’s Navigation Bar but what was the best way I found on the internet when I was looking for info. This also caused me some trouble when I tried to style the fileImporter
earlier!
structMyAppView: View {
init() { // Color Settings
UINavigationBar.appearance().tintColor = UIColor(named: "MyNavBarColor")
// ...
}
//...
}
The trouble started when I used toolbar(content:)
to customize my navigation bar:
// ...
.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())
}
})
The ToolbarItem
foreground color was ignored when UINavigationBar.appearance().tintColor
was set in init()
.
My solution
One of the application screen used navigationBarItems(leading:trailing:)
instead:
// ...
.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())
)
But it is now deprecated in favor of toolbar(content:)
with navigationBarLeading
or navigationBarTrailing
placement!
The Future
SwiftUI3.0 is just around the corner and customization will certainly improve.
Let's wait and see