I have been struggling for nearly a week to handle orientation changes. In a previous post
https://developer.apple.com/forums/thread/755957
I was strongly advised to use Size Classes, and I am trying to do that. by following this post:
https://forums.developer.apple.com/forums/thread/126878)
But I still can get it to work, so far I am just trying to initialize all the variables I will use later on. please bear with me I am 65 and have not done any coding for coming for 40 years. This my latest effort:
import SwiftUI
final class myOrientationChange: ObservableObject {
@Published var myOrient: String = ""
@Environment(\.verticalSizeClass) var myVertClass: UserInterfaceSizeClass?
@Environment(\.horizontalSizeClass) var myHorizClass: UserInterfaceSizeClass?
var _observer: NSObjectProtocol?
if myHorizClass == .compact && myVertClass == .regular {
self.myOrient = "Portrait"
} elseif myHorizClass == .regular && myVertClass == .compact {
self.myOrient = "Landscape"
} else {
self.myOrient = "Something Else"
}
}
struct ContentView: View {
@EnvironmentObject var envOrient: myOrientationChange
var body: some View {
VStack {
Image(systemName: "globe")
.imageScale(.large)
.foregroundStyle(.tint)
Text("Hello, world!")
Text("Orientation is \(envOrient.myOrient)")
}
.padding()
}
}
#Preview {
ContentView()
}
I will go on to use the NotificationCenter to trap there change of orientation even.
On the line if myHorizClass == .........
It tells me "Expected declaration in declaration of 'myOrientChange'"
What have I done wrong?
The issue you have is that the if statement is placed inline inside the class and Swift doesn't know what to do with it. This is where variable and function declarations go and not code blocks or expressions.
Instead, I think you want to put it in an initialiser, like this:
init() {
if myHorizClass == .compact && myVertClass == .regular {
self.myOrient = "Portrait"
} else if myHorizClass == .regular && myVertClass == .compact {
self.myOrient = "Landscape"
} else {
self.myOrient = "Something Else"
}
}
Also, I don't know if it was a typo or not, but in the if statement you had elseif
instead of else if
.
Does this solve your problem?