Swift 5.2 iOS 14
Trying to understand the Combine Framework in SwiftUI and put this code together using an example I found on the web. But ... the example wasn't complete.
Now when I change the orientation of my device, it does write to orientation, but how do I use this in my main loop? I cannot seem to find anything to subscribe too so I tried just using a onChange. Sadly that doesn't work.
class SizeClassViewV: ObservableObject {
@Environment(.verticalSizeClass) var verticalSizeClass: UserInterfaceSizeClass?
@Environment(.horizontalSizeClass) var horizontalSizeClass: UserInterfaceSizeClass?
enum Orientation {
case portrait
case landscape
}
@Published var orientation: Orientation = .portrait
private var listener: AnyCancellable?
init() {
if horizontalSizeClass == .compact && verticalSizeClass == .regular {
orientation = .portrait
} else if horizontalSizeClass == .regular && verticalSizeClass == .compact {
orientation = .landscape
}
listener = NotificationCenter.default.publisher(for: UIDevice.orientationDidChangeNotification)
.compactMap { ($0.object as? UIDevice)?.orientation }
.compactMap { deviceOrientation -> Orientation? in
if deviceOrientation.isPortrait {
return .portrait
} else if deviceOrientation.isLandscape {
return .landscape
} else {
return nil
}
}
.assign(to: .orientation, on: self)
}
deinit {
listener?.cancel()
}
}
In my main loop looks like this right now?
struct ContentView: View {
@State var orient = SizeClassViewX()
var body: some View {
Text("foo")
.onChange(of: orient.orientation) { ( _ ) in
print("changed")
}
}
}
Changed is never printed when I change the orientation?
question from:
https://stackoverflow.com/questions/65922994/basic-use-of-the-combine-framework 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…