2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【SwiftUI】MenuBarExtraが開かれた事を検知する

Posted at

はじめに

menuBarExtraStyle(.window)で閉じたことを検知したかったのですが、未だに出来ていません。
わかる方いたらコメントください。

いろいろ試してたら開いたことを検知できたので記録しておきます。

やりかた

import SwiftUI
import Combine
import AppKit

final class AppModel: ObservableObject {
    private var cancellable = Set<AnyCancellable>()

    init() {
        NotificationCenter.default.publisher(for: NSWindow.didBecomeKeyNotification)
            .sink { _ in
                print("✅")
            }
            .store(in: &cancellable)
    }
}

@main
struct swiftui_menubarextra_sampleApp: App {
    @StateObject private var appModel = AppModel()
    var body: some Scene {
        MenuBarExtra {
            ContentView()
        } label: {
            Image(systemName: "folder.fill")
        }
        .menuBarExtraStyle(.window)
    }
}

おわり

didBecomeKeyNotificationは監視対象のウインドウが一番前に来た時に通知するもの??かな??

2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?