Created
August 6, 2020 01:31
-
-
Save funway/1c28c11af5b130b585dd860cbbf80e97 to your computer and use it in GitHub Desktop.
View with NSWindowDelegate, listens window events
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import SwiftUI | |
struct TimerTest: View { | |
@State var date = Date() | |
@State var showSubView = false | |
var windowDelegate: MyWindowDelegate = MyWindowDelegate() | |
var body: some View { | |
ZStack{ | |
if showSubView { | |
VStack { | |
Text(" Timer Stoped?") | |
Button("Back") { | |
self.showSubView = false | |
} | |
} | |
} | |
else { | |
VStack { | |
Button("Switch to subview"){ | |
self.showSubView = true | |
} | |
Text("date: \(date)") | |
.onAppear(perform: { | |
self.windowDelegate.timer = Timer.scheduledTimer(withTimeInterval: 1, | |
repeats: true, | |
block: {_ in | |
self.date = Date() | |
NSLog("🔷 onAppear timer triggered") | |
}) | |
}) | |
.onDisappear(perform: { | |
self.windowDelegate.timer?.invalidate() | |
self.windowDelegate.timer = nil | |
NSLog("🔶 onDisappear stop timer") | |
}) | |
} | |
} | |
} | |
.frame(width: 500, height: 300) | |
} | |
class MyWindowDelegate: NSObject, NSWindowDelegate { | |
var timer: Timer? | |
func windowWillClose(_ notification: Notification) { | |
NSLog("🐶 window will close. Stop timer") | |
self.timer?.invalidate() | |
self.timer = nil | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment