首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在EnvironmentObject中从一个抖动手势(使用UIKit)设置SwiftUI不会更新视图

在EnvironmentObject中从一个抖动手势(使用UIKit)设置SwiftUI不会更新视图
EN

Stack Overflow用户
提问于 2020-02-10 19:57:43
回答 1查看 915关注 0票数 1

我希望通过物理摇动设备来触发SwiftUI功能。由于此时运动检测不是SwiftUI的一种功能,所以我需要使用UIKit集成和协调器返回一个Bool值,该值将指示设备已被震动,从而触发SwiftUI函数。

下面的代码都能很好地识别设备的抖动(这是由独立的“makeShakerSound()”函数所证明的,该函数在被震动时会播放声音剪辑,而且效果很好)。除了识别震动的工作代码之外,下面还包括了从ShakableViewRepresentable(isShaken:$shakeOccurred)调用ContentView的代码。

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

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

我很抱歉-我对此有点陌生。

代码语言:javascript
复制
/* 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 */
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-02-11 15:00:05

示例

代码语言:javascript
复制
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()
    }
}

只需取消评论行

代码语言:javascript
复制
let objectWillChange = ObservableObjectPublisher()

它就停止工作了。

不重新定义您自己的ObservableObjectPublisher()

已选中

代码语言:javascript
复制
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中

代码语言:javascript
复制
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()
        }
    }

它如预期的那样工作。

好的,用你的探测器

代码语言:javascript
复制
myDevice?.isShaken = true

永远不会运行,仅仅因为myDevice是零

解决方案

使您的模型具有全局可用性,因为在SwiftUI中,我们没有工具可以使其对ShakableViewController可用,也没有将其用作init的参数

SwiftDelegate.swift

代码语言:javascript
复制
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

代码语言:javascript
复制
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())
    }
}

至少在我的设备上是有效的:-)

没有声音,但它打印出来了

代码语言:javascript
复制
true
false
true
false
true

为每一个摇动的客人

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/60157510

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档