我发现当我滚动或刷新scrollView时“我的意思是从上到下滚动并释放”我的TimeModel因未知原因停止工作,在ScrollView上滚动卡住了应用程序中的所有内容,我想知道你是否看到过这样的情况一个问题,或者我们如何解决它?谢谢大家。我还制作了一个 gif,你可以看到问题。
import SwiftUI
struct ContentView: View {
@StateObject var timeModel: TimeModel = TimeModel()
var body: some View {
ScrollView() {
ForEach(0...10, id:\.self) { _ in
Text("Hello, world!")
.bold()
.padding()
}
}
Button("Start Timer") { timeModel.startTimer() }.padding()
}
}
class TimeModel: ObservableObject {
var timer: Timer = Timer()
func startTimer() {
timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(timerFunction), userInfo: nil, repeats: true)
}
@objc private func timerFunction() {
print("Tik!")
}
}
最佳答案
来自The ultimate guide to Timer :
Working with runloops
One common problem folks hit when using timers is that they won’t fire when the user is interacting with your app. For example, if the user has their finger touching the screen so they can scroll through a table view, your regular timers won’t get fired.
This happens because we’re implicitly creating our timer on the defaultRunLoopMode, which is effectively the main thread of our application. This will then get paused while the user is actively interacting with our UI, then reactivated when they stop.
The easiest solution is to create the timer without scheduling it directly, then add it by hand to a runloop of your choosing. In this case, .common is the one we want: it allows our timers to fire even when the UI is being used.
解决方案是在 RunLoop
上以 common
模式运行计时器:
func startTimer() {
timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(timerFunction), userInfo: nil, repeats: true)
RunLoop.current.add(timer, forMode: .common) // add this line
}
关于swift - 一起使用 Timer 和 ScrollView 的奇怪错误或问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65709047/