簡體   English   中英

將 @EnvironmentObject 屬性與 CADisplayLink 結合使用

[英]Using @EnvironmentObject properties with CADisplayLink

我正在嘗試為某些動畫實現CADisplayLink ,但是當我嘗試從MyAnimations類內部訪問我的MainData環境對象屬性時,我收到了致命錯誤No ObservableObject of type MainData found. A View.environmentObject(_:) for MainData may be missing as an ancestor of this view. No ObservableObject of type MainData found. A View.environmentObject(_:) for MainData may be missing as an ancestor of this view.

在 SceneDelegate 中,我將MainData設置為ContentView上的環境對象:

class SceneDelegate: UIResponder, UIWindowSceneDelegate {

    var window: UIWindow?

    var mainData = MainData()

    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()

        // Use a UIHostingController as window root view controller.
        if let windowScene = scene as? UIWindowScene {
            let window = UIWindow(windowScene: windowScene)
            
            window.rootViewController = UIHostingController(rootView: contentView.environmentObject(self.mainData))
            
            self.window = window
            window.makeKeyAndVisible()
        }
    }

...

}

這是帶有CADisplayLink的類。 createDisplayLink()ContentView調用:

class MyAnimations: NSObject{
    @EnvironmentObject var mainData: MainData

    
    func createDisplayLink() {
        let displaylink = CADisplayLink(target: self, selector: #selector(step))
        
        displaylink.add(to: .current, forMode: RunLoop.Mode.default)
    }
    

    @objc func step(link: CADisplayLink) {
        mainData.displayLinkY += 1.5   //Error here
        mainData.displayLinkX += 1.5
    }
    
    
} 

我的問題是:如何從step()內部更改環境對象屬性displayLinkXdisplayLinkY

只需刪除@EnvironmentObject屬性包裝器,它僅適用於 SwiftUI

class MyAnimations: NSObject{
    var mainData: MainData

    init(mainData: MainData) {
      self.mainData = mainData
        super.init()
    }

    // ... other code
}

暫無
暫無

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

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