SwiftUI's behaviour seems to follow through to the next view e.g. the navigationTitle will be emboldened and justified to leading edge.
However, with multiple collectionView cells on a view, scrolling them toward the top of the view will then move the navigationTitle into the menu bar at the top and centre it.
I noticed that if I do not do this and click on a cell to navigate to a new view that that view will also have its navigationTitle emboldened and justified to the leading edge of the screen.
Likewise, if the user has scrolled cells upward, to move that navigationTitle to the top and centre, then the next view will do the same.
I would like to ensure that even if the navigationTitle has moved to the centre (from an upward scrolling action) that the next view navigated to resets to ensure that the navigationTitle is emboldened and from the leading edge.
import SwiftUI
enum TestData: String, CaseIterable {
case title1, title2, title3, title4, title5
var description: String {
return self.rawValue
}
}
struct TestItem: Identifiable {
let id = UUID()
let data: TestData
}
let dataset: [TestItem] = []
struct TestTitleView: View {
let testData: [TestData] = [.title1, .title2, .title3, .title4, .title5]
var body: some View {
NavigationView {
ScrollView {
LazyVGrid(columns: [GridItem(.flexible())], spacing: 0) {
ForEach(testData, id: \.self) { data in
NavigationLink(destination: TestSegueView(data: data)) {
DataCell(data: data)
}
}
}
}
.navigationTitle("Test Data")
.navigationBarTitleDisplayMode(.large)
}
}
}
struct DataCell: View {
let data: TestData
var body: some View {
Text(data.description.capitalized)
.frame(maxWidth: .infinity)
.frame(height: UIScreen.main.bounds.height / 5)
.background(Color.gray)
.foregroundColor(.black)
.cornerRadius(25)
.padding(5)
}
}
struct TestSegueView: View {
@State var data: TestData
var body: some View {
VStack {
ScrollView(.vertical) {
LazyVGrid(columns: [GridItem(.flexible(), spacing: 10), GridItem(.flexible(), spacing: 10)], spacing: 10) {
ForEach(dataset.filter { $0.data == self.data }) { item in
DataItemTile(item: item)
.frame(maxWidth: .infinity) // Expand cell width to fill the grid column
}
}
.padding()
}
}
.frame(maxWidth: .infinity)
.navigationBarTitle(data.description.capitalized, displayMode: .large) // Set display mode to large
.navigationBarItems(trailing:
Button(action: {
print("Button pressed !")
}) {
Image(systemName: "plus")
}
)
}
}
struct DataItemTile: View {
let item: TestItem
var body: some View {
Text(item.data.description)
}
}
I have set the navigationBarTitleDisplayMode to .large, but SwiftUI seems to override the desired behaviour that I am looking for.