【发布时间】:2021-01-05 05:01:49
【问题描述】:
我正在尝试检测设备何时在 iPad 上和纵向模式。
目前我在 UIKit 中使用UIDevice API 并使用环境对象来观察变化。我使用这里找到的解决方案 - Determining Current Device and Orientation。
但是,orientationInfo.orientation 最初始终等于 .portrait,直到旋转为纵向,然后再返回横向。
所以在执行以下操作时显示FABView
struct HomeView: View {
@EnvironmentObject var orientationInfo: OrientationInfo
let isPhone = UIDevice.current.userInterfaceIdiom == .phone
var body: some View {
ZStack(alignment: .bottom) {
#if os(iOS)
if isPhone == false && orientationInfo.orientation == .portrait {
FABView()
}
#endif
}
}
}
当 iPad 最初处于横向时会加载视图,但在更改为纵向并返回横向时会被删除。为什么会发生这种情况?如何确保在首次加载时未加载视图?
完整代码
struct HomeTab: View {
var body: some View {
NavigationView {
HomeView()
.environmentObject(OrientationInfo())
}
}
}
struct HomeView: View {
@EnvironmentObject var orientationInfo: OrientationInfo
let isPhone = UIDevice.current.userInterfaceIdiom == .phone
var body: some View {
ZStack(alignment: .bottom) {
#if os(iOS)
if isPhone == false && orientationInfo.orientation == .portrait {
FABView()
}
#endif
}
}
}
final class OrientationInfo: ObservableObject {
enum Orientation {
case portrait
case landscape
}
@Published var orientation: Orientation
private var _observer: NSObjectProtocol?
init() {
// fairly arbitrary starting value for 'flat' orientations
if UIDevice.current.orientation.isLandscape {
self.orientation = .landscape
}
else {
self.orientation = .portrait
}
// unowned self because we unregister before self becomes invalid
_observer = NotificationCenter.default.addObserver(forName: UIDevice.orientationDidChangeNotification, object: nil, queue: nil) { [unowned self] note in
guard let device = note.object as? UIDevice else {
return
}
if device.orientation.isPortrait {
self.orientation = .portrait
}
else if device.orientation.isLandscape {
self.orientation = .landscape
}
}
}
deinit {
if let observer = _observer {
NotificationCenter.default.removeObserver(observer)
}
}
}
【问题讨论】: