Reputation: 1247
I'm trying to change the first characters font color in SwiftUI like this
But I'm getting the warning saying Only unstyled text can be used with navigationTitle(_:)
when I run the app, and the text shows up as black. Since I don't want to change the whole font - changing the font color of the navigationBar is not an option. Is the only way to go to make a custom NavigationBar?
The app has iOS 14 as minimum requirements.
This is my current try for a solution... but then the whole title turns black, since styled text isn't allowed.
let titleToSet = (Text("M").foregroundColor(Color.red) + Text("y page")
NavigationView {
contentView()
.navigationTitle(titleToSet)
}
Upvotes: 1
Views: 981
Reputation: 9695
You can place any kind of view you want in the .toolbar
. It doesn't have to be a button. You can roll your own title view. So, that just leaves the view itself. If you want to simply make the first letter red, then the simplest way of creating this view is by concatenating your text, after you remove the first letter from the remaining title text.
struct ToolBarStyledText: View {
var body: some View {
Text("Hello, World!")
.toolbar {
ToolbarItem(placement: .navigationBarLeading) {
TitleView("My page")
}
ToolbarItem(placement: .navigationBarTrailing) {
Image(systemName: "person.circle")
}
}
}
}
struct TitleView: View {
let firstLetter: String
let remainingText: String
init(_ title: String) {
var text = title
if !text.isEmpty {
firstLetter = String(text.removeFirst())
remainingText = text
} else {
firstLetter = ""
remainingText = ""
}
}
var body: some View {
Text(firstLetter).foregroundColor(.red).bold() + Text(remainingText).bold()
}
}
Upvotes: 2