SwiftUI 在设备旋转时重绘视图组件 [英] SwiftUI Repaint View Components on Device Rotation

查看:48
本文介绍了SwiftUI 在设备旋转时重绘视图组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在 SwiftUI 中检测设备旋转并重新绘制视图组件?

How to detect device rotation in SwiftUI and re-draw view components?

当第一个出现时,我有一个 @State 变量初始化为 UIScreen.main.bounds.width 的值.但是当设备方向改变时,这个值不会改变.当用户更改设备方向时,我需要重绘所有组件.

I have a @State variable initialized to the value of UIScreen.main.bounds.width when the first appears. But this value doesn't change when the device orientation changes. I need to redraw all components when the user changes the device orientation.

推荐答案

@dfd 提供了两个不错的选择,我添加了第三个,这是我使用的.

@dfd provided two good options, I am adding a third one, which is the one I use.

在我的例子中,我继承了 UIHostingController,在函数 viewWillTransition 中,我发布了一个自定义通知.

In my case I subclass UIHostingController, and in function viewWillTransition, I post a custom notification.

然后,在我的环境模型中,我会监听此类通知,然后可以在任何视图中使用.

Then, in my environment model I listen for such notification which can be then used in any view.

struct ContentView: View {
    @EnvironmentObject var model: Model

    var body: some View {
        Group {
            if model.landscape {
                Text("LANDSCAPE")
            } else {
                Text("PORTRAIT")
            }
        }
    }
}

在 SceneDelegate.swift 中:

In SceneDelegate.swift:

window.rootViewController = MyUIHostingController(rootView: ContentView().environmentObject(Model(isLandscape: windowScene.interfaceOrientation.isLandscape)))

我的 UIHostingController 子类:

My UIHostingController subclass:

extension Notification.Name {
    static let my_onViewWillTransition = Notification.Name("MainUIHostingController_viewWillTransition")
}

class MyUIHostingController<Content> : UIHostingController<Content> where Content : View {

    override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
        NotificationCenter.default.post(name: .my_onViewWillTransition, object: nil, userInfo: ["size": size])
        super.viewWillTransition(to: size, with: coordinator)
    }

}

还有我的模型:

class Model: ObservableObject {
    @Published var landscape: Bool = false

    init(isLandscape: Bool) {
        self.landscape = isLandscape // Initial value
        NotificationCenter.default.addObserver(self, selector: #selector(onViewWillTransition(notification:)), name: .my_onViewWillTransition, object: nil)
    }

    @objc func onViewWillTransition(notification: Notification) {
        guard let size = notification.userInfo?["size"] as? CGSize else { return }

        landscape = size.width > size.height
    }
}

这篇关于SwiftUI 在设备旋转时重绘视图组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆