swift - 一起使用 Timer 和 ScrollView 的奇怪错误或问题

标签 swift swiftui

我发现当我滚动或刷新scrollView时“我的意思是从上到下滚动并释放”我的TimeModel因未知原因停止工作,在ScrollView上滚动卡住了应用程序中的所有内容,我想知道你是否看到过这样的情况一个问题,或者我们如何解决它?谢谢大家。我还制作了一个 gif,你可以看到问题。

enter image description here

 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/

相关文章:

ios - 在显示转场时隐藏 UITabbar 并显示工具栏

swift - Alamofire 2.0 的放置请求失败

ios - 使用固定的 "Header"在 UITableView 上滚动单元格

macos - macOS 上的 SwiftUI ListStyle

ios - 使用 Geometry Reader 和 ScrollVIew 时,SwiftUI View 向右偏移

ios - 在 Swift 4 中解码 JSON 时遇到问题

swift - 静态方法只能在类型上声明

swift - 如何在 SwiftUI 中获得弹跳动画?

ios - 右侧带有部分索引的 SwiftUI 列表?

ios - SwiftUI 无法调整图像大小