I want to create different layouts using size classes and I followed this example: https://www.hackingwithswift.com/quick-start/swiftui/how-to-create-different-layouts-using-size-classes
I extended the Xcode Master/Detail template and changed the ContentView as follows, with the two size classes and then using the horizontal size class to set a size class dependent navigation title. The problem is the navigation title would always read as "Compact". What am I missing here?
struct ContentView: View {
@Environment(\.managedObjectContext)
var viewContext
@Environment(\.verticalSizeClass) var vSizeClass
@Environment(\.horizontalSizeClass) var hSizeClass
var body: some View {
NavigationView {
MasterView()
.navigationBarTitle(Text(hSizeClass == .compact ? "Compact" : "Regular"))
.navigationBarItems(
leading: EditButton(),
trailing: Button(
action: {
withAnimation { Event.create(in: self.viewContext) }
}
) {
Image(systemName: "plus")
}
)
Text("Detail view content goes here")
.navigationBarTitle(Text("Detail"))
}.navigationViewStyle(DoubleColumnNavigationViewStyle())
}
}
I made my own test using this code, simplified, and slightly modified from yours:
struct ContentView: View {
@Environment(\.managedObjectContext)
var viewContext
@Environment(\.verticalSizeClass) var vSizeClass
@Environment(\.horizontalSizeClass) var hSizeClass
var body: some View {
NavigationView {
Form {
Section {
Text("My Content")
}
}
.navigationBarTitle(Text(hSizeClass == .compact ? "Compact" : "Regular"))
}
}
}
Testing it produces the desired results in the Simulator:
iPhone 8 Plus: Compact Width in Portrait Mode, Regular Width in Landscape Mode
Initially the Navigation Title shows "Compact", but when the phone is rotated to landscape orientation, the title updates, showing "Regular".
Just make sure you are testing using devices or simulators whose horizontal size class IS regular in some orientation.
Here is the official documentation on this topic, as mentioned in OP's comment. It has a handy table listing device size classes based on their model and physical orientation:
Apple Developer - Human Interface Guidelines: Adaptivity and Layout
Good luck!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With