#ios #swift #swiftui
#iOS #swift #swiftui
Вопрос:
На UIViewController
мы можем легко добавить наблюдателя в контроллер. Нравится:
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(self, selector: #selector(didTakeScreenshot(notification:)), name: UIApplication.userDidTakeScreenshotNotification, object: nil)
}
@objc func didTakeScreenshot(notification: Notification) {
print("Screen Shot Taken")
}
}
Или захват записи с:
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
let isCaptured = UIScreen.main.isCaptured
return true
}
Но как это сделать с помощью SwiftUI?
Ответ №1:
Вот простая демонстрация:
struct ContentView: View {
@State var isRecordingScreen = false
var body: some View {
Text("Test")
.onReceive(NotificationCenter.default.publisher(for: UIApplication.userDidTakeScreenshotNotification)) { _ in
print("Screenshot taken")
}
.onReceive(NotificationCenter.default.publisher(for: UIScreen.capturedDidChangeNotification)) { _ in
isRecordingScreen.toggle()
print(isRecordingScreen ? "Started recording screen" : "Stopped recording screen")
}
}
}