【发布时间】:2020-09-25 17:38:19
【问题描述】:
我正在尝试为某些动画实现CADisplayLink,但是当我尝试从类MyAnimations 中访问我的MainData 环境对象属性时,我收到了致命错误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() 内部更改环境对象属性displayLinkX 和displayLinkY?
【问题讨论】:
标签: swift swiftui cadisplaylink