如何在 SwiftUI 中检测设备旋转并重新绘制视图组件?
当第一个出现时,我有一个 @State 变量初始化为 UIScreen.main.bounds.width 的值。但当设备方向改变时,该值不会改变。当用户更改设备方向时,我需要重新绘制所有组件。
这是基于通知发布者的惯用 SwiftUI 实现:
struct ContentView: View {
@State var orientation = UIDevice.current.orientation
let orientationChanged = NotificationCenter.default.publisher(for: UIDevice.orientationDidChangeNotification)
.makeConnectable()
.autoconnect()
var body: some View {
Group {
if orientation.isLandscape {
Text("LANDSCAPE")
} else {
Text("PORTRAIT")
}
}.onReceive(orientationChanged) { _ in
self.orientation = UIDevice.current.orientation
}
}
}
发布者的输出(上面没有使用,因此_
作为块参数)也包含密钥"UIDeviceOrientationRotateAnimatedUserInfoKey"
in its userInfo
属性,如果您需要知道是否应该对旋转进行动画处理。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)