在CADisplayLink中使用@EnvironmentObject属性

时间:2020-09-25 17:38:19

标签: swift swiftui cadisplaylink

我正在尝试为某些动画实现CADisplayLink,但是当我尝试从类MainData内部访问MyAnimations环境对象属性时,出现致命错误{{1 }}

在SceneDelegate中,我将No ObservableObject of type MainData found. A View.environmentObject(_:) for MainData may be missing as an ancestor of this view.设置为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 } } 内部更改环境对象属性displayLinkXdisplayLinkY

1 个答案:

答案 0 :(得分:0)

只需删除@EnvironmentObject属性包装器,仅适用于SwiftUI

class MyAnimations: NSObject{
    var mainData: MainData

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

    // ... other code
}