![](/img/trans.png)
[英]Guidance needed on using CADisplayLink with tableViewCells
[英]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()
內部更改環境對象屬性displayLinkX
和displayLinkY
?
只需刪除@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.