【问题标题】:Setting EnvironmentObject from a Shake Gesture (using UIKit) in SwiftUI doesn't update View在 SwiftUI 中通过摇动手势(使用 UIKit)设置 EnvironmentObject 不会更新视图
【发布时间】:2020-02-10 19:57:43
【问题描述】:

我希望通过物理摇晃设备来触发 SwiftUI 功能。由于此时 SwiftUI 还没有运动检测功能,所以我需要使用 UIKit 集成和协调器返回一个 Bool 值,该值表示设备已被晃动,从而触发 SwiftUI 功能。

以下代码在识别设备的晃动方面都非常有效(独立的“makeShakerSound()”函数证明了这一点,该函数在晃动时播放声音片段,效果很好)。除了识别抖动的工作代码之外,我还包括了用于从 ContentView 调用 ShakableViewRepresentable(isShaken: $shakeOccurred) 的代码,如下所示。

我创建了一个 EnvironmentObject 来标记设备已被摇动,并使用 objectWillChange 来宣布发生了变化。

我的问题是这样的:当检测到晃动时,晃动的声音效果很好,但是我的 ContentView 没有更新环境对象 myDevice.isShaken 的变化。我认为使用 objectWillChange 可能会解决这个问题,但事实并非如此。我错过了什么?

抱歉 - 我对此有点陌生。

/* CREATE AN ENVIRONMENTAL OBJECT TO INDICATE DEVICE HAS BEEN SHAKEN */

import Combine
import SwiftUI

class MyDevice: ObservableObject {
    // let objectWillChange = ObservableObjectPublisher()
    var isShaken: Bool = false {
        willSet {
            self.objectWillChange.send()
        }
    }
}


/* DETECT SHAKE GESTURE AND FLAG THAT SHAKING HAS OCCURRED */

import UIKit
import SwiftUI

struct ShakableViewRepresentable: UIViewControllerRepresentable {

    class Coordinator: NSObject {
        var parent: ShakableViewRepresentable
        init(_ parent: ShakableViewRepresentable) {
            self.parent = parent
        }
    }

    func makeCoordinator() -> ShakableViewRepresentable.Coordinator {
        Coordinator(self)
    }

    func makeUIViewController(context: Context) -> ShakableViewController {
        ShakableViewController()
    }
    func updateUIViewController(_ uiViewController: ShakableViewController, context: Context) {}
}

class ShakableViewController: UIViewController {

    override func motionBegan(_ motion: UIEvent.EventSubtype, with event: UIEvent?) {
        guard motion == .motionShake else { return }

         /* SHAKING GESTURE WAS DETECTED */
        myDevice?.isShaken = true       /* ContentView doesn't update! */
        makeShakerSound()       /* This works great */

        /* I’M TRYING TO TRIGGER A FUNCTION IN SWIFTUI BY SHAKING THE DEVICE:  Despite setting the myDevice.isShaken environment object to "true", my ContentView doesn't update when the shaking gesture is detected.   */

    }
}


ContentView.swift

    @EnvironmentObject var myDevice: MyDevice

    var body: some View {
        NavigationView {

            ZStack {

                /* DETECT SHAKE GESTURE - This works */
                ShakableViewRepresentable()
                    .allowsHitTesting(false)

                VStack {
                    /* SHOW CURRENT STATE OF myDevice.isShaken - Doesn't update */
                    Text(self.myDevice.isShaken ? "The device has been shaken" : "No shaking has occurred")
                    Text("Device was shaken: \(self.myDevice.isShaken.description)")
                }

/* more views below */

【问题讨论】:

    标签: ios uikit swiftui combine shake


    【解决方案1】:

    例子

    import SwiftUI
    import Combine
    
    class MyDevice: ObservableObject {
        //let objectWillChange = ObservableObjectPublisher()
        var isShaken: Bool = false {
            willSet {
                self.objectWillChange.send()
            }
        }
    }
    struct ContentView: View {
        @ObservedObject var model = MyDevice()
        var body: some View {
            VStack {
                Text("\(model.isShaken.description)").onTapGesture {
                    self.model.isShaken.toggle()
                }
    
            }
        }
    }
    struct ContentView_Previews: PreviewProvider {
        static var previews: some View {
            ContentView()
        }
    }
    

    取消注释

    let objectWillChange = ObservableObjectPublisher()
    

    它停止工作。

    不要重新定义你自己的 ObservableObjectPublisher()

    检查

    import SwiftUI
    import Combine
    
    class MyDevice: ObservableObject {
        //let objectWillChange = ObservableObjectPublisher()
        var isShaken: Bool = false {
            willSet {
                self.objectWillChange.send()
            }
        }
    }
    struct ContentView: View {
        @EnvironmentObject var model: MyDevice
        var body: some View {
            VStack {
                Text("\(model.isShaken.description)").onTapGesture {
                    self.model.isShaken.toggle()
                }
    
            }
        }
    }
    struct ContentView_Previews: PreviewProvider {
        static var previews: some View {
            ContentView().environmentObject(MyDevice())
        }
    }
    

    在 SceneDelegate.swift 中

    func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
            // Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
            // If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
            // This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).
    
            // Create the SwiftUI view that provides the window contents.
            let contentView = ContentView().environmentObject(MyDevice())
            //let contentView = ContentView()
    
            // Use a UIHostingController as window root view controller.
            if let windowScene = scene as? UIWindowScene {
                let window = UIWindow(windowScene: windowScene)
                window.rootViewController = UIHostingController(rootView: contentView)
                self.window = window
                window.makeKeyAndVisible()
            }
        }
    

    它按预期工作。

    好的,使用震动检测器

    myDevice?.isShaken = true
    

    永远不会运行,因为 myDevice 是 nil

    解决办法

    使您的模型全局可用,因为在 SwiftUI 中我们没有工具如何使其可用于 ShakableViewController,或者将其用作其 init 的参数

    SwiftDelegate.swift

    import UIKit
    import SwiftUI
    
    let model = MyDevice()
    
    class SceneDelegate: UIResponder, UIWindowSceneDelegate {
    
        var window: UIWindow?
    
    
        func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
            // Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
            // If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
            // This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).
    
            // Create the SwiftUI view that provides the window contents.
            let contentView = ContentView().environmentObject(model)
            //let contentView = ContentView()
    
            // Use a UIHostingController as window root view controller.
            if let windowScene = scene as? UIWindowScene {
                let window = UIWindow(windowScene: windowScene)
                window.rootViewController = UIHostingController(rootView: contentView)
                self.window = window
                window.makeKeyAndVisible()
            }
        }
    
        func sceneDidDisconnect(_ scene: UIScene) {
            // Called as the scene is being released by the system.
            // This occurs shortly after the scene enters the background, or when its session is discarded.
            // Release any resources associated with this scene that can be re-created the next time the scene connects.
            // The scene may re-connect later, as its session was not neccessarily discarded (see `application:didDiscardSceneSessions` instead).
        }
    
        func sceneDidBecomeActive(_ scene: UIScene) {
            // Called when the scene has moved from an inactive state to an active state.
            // Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive.
        }
    
        func sceneWillResignActive(_ scene: UIScene) {
            // Called when the scene will move from an active state to an inactive state.
            // This may occur due to temporary interruptions (ex. an incoming phone call).
        }
    
        func sceneWillEnterForeground(_ scene: UIScene) {
            // Called as the scene transitions from the background to the foreground.
            // Use this method to undo the changes made on entering the background.
        }
    
        func sceneDidEnterBackground(_ scene: UIScene) {
            // Called as the scene transitions from the foreground to the background.
            // Use this method to save data, release shared resources, and store enough scene-specific state information
            // to restore the scene back to its current state.
        }
    
    
    }
    

    ContentView.swift

    import SwiftUI
    import Combine
    
    struct ShakableViewRepresentable: UIViewControllerRepresentable {
    
        class Coordinator: NSObject {
            var parent: ShakableViewRepresentable
            init(_ parent: ShakableViewRepresentable) {
                self.parent = parent
            }
        }
    
        func makeCoordinator() -> ShakableViewRepresentable.Coordinator {
            Coordinator(self)
        }
    
        func makeUIViewController(context: Context) -> ShakableViewController {
            ShakableViewController()
        }
        func updateUIViewController(_ uiViewController: ShakableViewController, context: Context) {}
    }
    
    class ShakableViewController: UIViewController {
        override func motionBegan(_ motion: UIEvent.EventSubtype, with event: UIEvent?) {
            guard motion == .motionShake else { return }
    
            model.isShaken.toggle()
            print(model.isShaken)
    
    
        }
    }
    
    
    class MyDevice: ObservableObject {
        //let objectWillChange = ObservableObjectPublisher()
        var isShaken: Bool = false {
            willSet {
                self.objectWillChange.send()
            }
        }
    }
    struct ContentView: View {
        @EnvironmentObject var model: MyDevice
        var body: some View {
            VStack {
                ShakableViewRepresentable()
                                   .allowsHitTesting(false)
                Text(self.model.isShaken ? "The device has been shaken" : "No shaking has occurred").onTapGesture {
                    self.model.isShaken.toggle()
                }
    
            }
        }
    }
    struct ContentView_Previews: PreviewProvider {
        static var previews: some View {
            ContentView().environmentObject(MyDevice())
        }
    }
    

    而且它可以工作,至少在我的设备上 :-)

    没有声音,但会打印

    true
    false
    true
    false
    true
    

    每一次摇一摇的客串

    【讨论】:

    • 我注释掉了有问题的代码行。该应用程序编译并成功运行,但不幸的是结果相同 - 当 UIKit 中的摇动手势更新我的环境对象时,ContentView 仍未更新(mydevice?.isShaken = true)。
    • 我也使用 EnvironmentObject 进行了检查...您是否将它暴露给您的 ContentView?
    • 这可能就是我所缺少的。正如我所说,我有点新手,所以如果我错过了一些基本的东西,我很抱歉。在上面的 ContentView 摘录中,我包括“@EnvironmentObject var myDevice: MyDevice”,以及一些调用 self.myDevice 的文本视图。对 myDevice 的更改是在 ShakableViewController: UIViewController 类中进行的(因为 soundFX 代码有效,所以它被成功调用)。我还需要将它暴露给 ContentView 吗?
    • 我更新了答案,看到这一行 let contentView = ContentView().environmentObject(MyDevice())
    • 别担心,更有经验的 SwiftUI 用户不知道它是如何工作的 :-) 一开始缺少(或非常不清楚)来自 Apple 的文档。
    猜你喜欢
    • 1970-01-01
    • 2020-09-27
    • 1970-01-01
    • 2020-03-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-27
    • 2021-11-12
    相关资源
    最近更新 更多