[英]How can I run an action coming from View in a Timer inside a class in SwiftUI?
我想在我的 class 中運行一個Void
動作,這個動作來自我的視圖,目前它是第一次運行,然后拋出EXC_BAD_ACCESS
錯誤。 我知道我在兩者之間遺漏了一些東西,但找不到它,需要幫助。
struct ContentView: View {
@StateObject var customTimer: CustomTimer = CustomTimer()
var body: some View {
VStack(spacing: 30.0) {
Button("start timer") {
customTimer.timerFunction(action: { print("Hello") })
customTimer.startTimer(timeInterval: 1.0) //<<: Thread 1: EXC_BAD_ACCESS (code=1, address=0x4d555460)
}
Button("stop timer") {
customTimer.stopTimer()
}
}
.font(Font.body.bold())
}
}
class CustomTimer: ObservableObject {
private var timer: Timer = Timer()
func startTimer(timeInterval: Double) {
timer = Timer.scheduledTimer(timeInterval: timeInterval, target: self, selector: #selector(timerFunction), userInfo: nil, repeats: true)
RunLoop.current.add(timer, forMode: .common)
timer.tolerance = 0.0
}
func stopTimer() { timer.invalidate() }
@objc func timerFunction(action: () -> Void) { action() }
}
我發現了問題,我應該為此定義一個閉包,如下所示:
var action: () -> Void = {}
如果您發現有任何改進,請告訴我,謝謝
struct ContentView: View {
@StateObject var customTimer: CustomTimer = CustomTimer()
var body: some View {
VStack(spacing: 30.0) {
Button("start timer") {
customTimer.action = { print("Hello") }
customTimer.startTimer(timeInterval: 1.0)
}
Button("stop timer") {
customTimer.stopTimer()
}
}
.font(Font.body.bold())
}
}
class CustomTimer: ObservableObject {
private var timer: Timer = Timer()
var action: () -> Void = {}
func startTimer(timeInterval: Double) {
timer = Timer.scheduledTimer(timeInterval: timeInterval, target: self, selector: #selector(timerFunction), userInfo: nil, repeats: true)
RunLoop.current.add(timer, forMode: .common)
timer.tolerance = 0.0
}
func stopTimer() { timer.invalidate() }
@objc private func timerFunction() { action() }
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.