在尝试使用 Timer.scheduledTimer 的 SwiftUI 代码中获取未解析的标识符“self" [英] getting unresolved identifier 'self' in SwiftUI code trying to use Timer.scheduledTimer
问题描述
在 SwiftUI 中,我注意到使用一个定时器:
In SwiftUI I'm noting to use a Timer that:
尝试 1 - 这不能作为获取使用未解析的标识符‘自我’"
Try 1 - This doesn't work as get "Use of unresolved identifier 'self'"
var timer2: Timer = Timer.scheduledTimer(withTimeInterval: 1, repeats: true) {
self.angle = self.angle + .degrees(1)
}
尝试 2 - 有效,但必须输入_ = self.timer"才能稍后启动
Try 2 - Works, but have to put in an "_ = self.timer" to start it later
var timer: Timer {
Timer.scheduledTimer(withTimeInterval: 0.1, repeats: true) {_ in
self.angle = self.angle + .degrees(1)
}
}
// then after need to use " .onAppear(perform: {_ = self.timer}) "
有没有办法让我的 Try1 工作?那是我可以在 SwiftUI 文件中预先创建计时器的地方吗?或者实际上在 SwiftUI 中的哪个位置通常会启动和停止计时器?即生命周期方法在哪里
Is there a way to get my Try1 working? That is where in a SwiftUI file I can create the timer up front? Or actually where in SwiftUI would one normally start and stop the timer? i.e. where are lifecycle methods
整个文件:
import SwiftUI
struct ContentView : View {
@State var angle: Angle = .degrees(55)
// var timer2: Timer = Timer.scheduledTimer(withTimeInterval: 1, repeats: true) {
// self.angle = self.angle + .degrees(1)
// }
var timer: Timer {
Timer.scheduledTimer(withTimeInterval: 0.1, repeats: true) {_ in
self.angle = self.angle + .degrees(1)
}
}
private func buttonAction() {
print("test")
self.angle = self.angle + .degrees(5)
}
var body: some View {
VStack{
Text("Start")
ZStack {
Circle()
.fill(Color.blue)
.frame(
width: .init(integerLiteral: 100),
height: .init(integerLiteral: 100)
)
Rectangle()
.fill(Color.green)
.frame(width: 20, height: 100)
// .rotationEffect(Angle(degrees: 25.0))
.rotationEffect(self.angle)
}
Button(action: self.buttonAction) {
Text("CLICK HERE")
}
Text("End")
}
.onAppear(perform: {_ = self.timer})
}
}
推荐答案
我不清楚您的示例是否需要一个计时器,但由于存在大量关于如何包含计时器的错误信息在 SwiftUI 应用中,我将进行演示.
It isn't clear to me that you need a timer for your example, but since there is a great deal of misinformation out there about how to include a Timer in a SwiftUI app, I'll demonstrate.
关键是把定时器放在别处,每次触发时发布.我们可以通过添加一个类来轻松地做到这一点,该类将计时器作为可绑定对象保存到我们的环境中(请注意,您需要导入 Combine):
The key is to put the timer elsewhere and publish each time it fires. We can easily do this by adding a class that holds the timer as a bindable object to our environment (note that you will need to import Combine):
class TimerHolder : BindableObject {
var timer : Timer!
let didChange = PassthroughSubject<TimerHolder,Never>()
var count = 0 {
didSet {
self.didChange.send(self)
}
}
func start() {
self.timer?.invalidate()
self.count = 0
self.timer = Timer.scheduledTimer(withTimeInterval: 1, repeats: true) {
[weak self] _ in
guard let self = self else { return }
self.count += 1
}
}
}
我们需要通过环境向下传递这个类的实例,因此我们修改场景委托:
We will need to pass an instance of this class down through the environment, so we modify the scene delegate:
window.rootViewController =
UIHostingController(rootView: ContentView())
变成
window.rootViewController =
UIHostingController(rootView: ContentView()
.environmentObject(TimerHolder()))
最后,让我们放一些启动计时器并显示计数的 UI,以证明它正在工作:
Finally, lets put up some UI that starts the timer and displays the count, to prove that it is working:
struct ContentView : View {
@EnvironmentObject var timerHolder : TimerHolder
var body: some View {
VStack {
Button("Start Timer") { self.timerHolder.start() }
Text(String(self.timerHolder.count))
}
}
}
EDIT 为那些没有关注剧情的人更新:BindableObject 已经迁移到 ObservableObject,不再需要手动发送信号.所以:
EDIT Update for those who have not been following the plot: BindableObject has migrated into ObservableObject, and there is no need any more for manual signalling. So:
class TimerHolder : ObservableObject {
var timer : Timer!
@Published var count = 0
// ... and the rest is as before ...
这篇关于在尝试使用 Timer.scheduledTimer 的 SwiftUI 代码中获取未解析的标识符“self"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!