본문 바로가기
공부/스위프트

[스위프트] SwiftUI Command Group으로 상단 메뉴 만들기

by 초코팅촉 2024. 5. 13.
728x90

맥용앱에서 프로그램 실행하면 좌상단에 나오는 각종 메뉴의 추가 방법에 대해 알아봅시다!

 

좌측 상단 메뉴들

좌측 상단 메뉴들

위와 같이 좌측 상단에 애플 로고와 함께 있는 메뉴들입니다.(기본메뉴? 아님 앱 자체 메뉴? 뭐 그런거같아요? 용어가 뭔지 모르겠넹;;)

기본적인 선언방식은 다음과 같이 두가지로 있습니다.

CommandMenu(<메뉴 이름>) { content 클로저 }

CommandGroup(before:) { content 클로저 }
CommandGroup(after:) { content 클로저 }
CommandGroup(replacing:) { content 클로저 }

 

실제로 써볼까요?

우선 현재 진행중인 프로젝트의 ~~App.swift 파일로 가야 합니다.

import SwiftUI

@main
struct SampleApp: App {
    var body: some Scene {
        WindowGroup {
            ContentView()
        }
        .commands {
            // 아래와 같이 새로운 CommandMenu를 만들 수 있다.
            CommandMenu("My Top Menu") {
                  Button("Sub Menu Item") { print("You pressed sub menu.") }
                      .keyboardShortcut("S")
            }
            
            //혹은 아래처럼 CommandGroup을 Button들로 만든다음 before, after, replacing 파라미터에 맞춰서 마음대로 위치를 지정할 수 있다.
            CommandGroup(after: .newItem) {
                Button("Save") { }
                .keyboardShortcut(KeyEquivalent("s"), modifiers: .command)
                
                Button("Save As") { }
                .keyboardShortcut(KeyEquivalent("s"), modifiers: .command.union(.shift))
            }
        }
    }
}

 

1. WindowGroup에 .commands{}를 추가해줍니다.

2. 11번 줄처럼 선언하면 View와 Window 사이에 메뉴들이 추가됩니다.

3. 17번 줄처럼 매개변수에 CommandGroupPlacement타입의 구조체를 각각 

    • before : 지정된 매개변수 이전에 배치

    • after : 지정된 매개변수 이후에 배치

    • replacing : 지정된 매개변수를 대체해서 해당위치에 배치

    이렇게 세가지로 둡니다.

4. 각 후행 클로저 안에 원하는 Button 혹은 Menu를 배치합니다.

 

쓰는방법은 크게 어렵지 않아요 그쵸?

다음에 기회가 된다면 fileExporter와 fileImporter를 같이 쓰는 예시를 한번 보여드리고 싶네요...

fileImporter와 fileExporter는 각각 SwiftUI에서 `NSOpenPanel`과 `NSSavePanel`에 대응하도록 만든것이라고 합니다.

 

다음의 사이트를 참고했습니다.

https://forums.developer.apple.com/forums/thread/668139

 

How do I add MenuItem to menubar i… | Apple Developer Forums

  You’re now watching this thread. If you’ve opted in to email or web notifications, you’ll be notified when there’s activity. Click again to stop watching or visit your profile to manage watched threads and notifications.   You’ve stopped watc

forums.developer.apple.com