簡體   English   中英

在 SwiftUI 中通過搖動手勢(使用 UIKit)設置 EnvironmentObject 不會更新視圖

[英]Setting EnvironmentObject from a Shake Gesture (using UIKit) in SwiftUI doesn't update View

我希望通過物理搖動設備來觸發 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 */

例子

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 為零

解決方案

使您的模型全局可用,因為在 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.
    }


}

內容視圖.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

每一次搖晃客人

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM