What is this?
A guide to opening a new window using SwiftUI when developing an app for macOS.
Environment
- Apple Silicon M1 MacBook Air
- 16 Gb
- macOS Sequoia 15.0
- Xcode Version 16.0 (16A242d)
Steps
This time we'll build something where tapping a button in ContentView.swift opens PopupWindow.swift.
Set up the window
First, set up the window you want to open.
Here I'm using an arbitrary file name, PopupWindow.swift.
//
// PopupWindow.swift
// sample
//
//
import SwiftUI
import AVKit
struct PopupWindow: View {
var body: some View {
VStack {
Text("ポップアップウィンドウです")
}
.padding()
.frame(minWidth: 440, minHeight: 480)
}
}
#Preview {
PopupWindow()
}
Add a WindowGroup
Open the AppName App.swift file that gets created automatically when you create a project.
Add the following to it.
//
// アプリ名App.swift
// sample
//
//
import SwiftUI
@main
struct FolderCustomizerApp: App {
var body: some Scene {
WindowGroup {
ContentView()
}
// ここを追記した
WindowGroup(id: "popup") {
PopupWindow()
}
}
}
Add the button
Finally, add a button to ContentView.Swift.
省略
Button(action: {
openWindow(id: "popup")
}) {
Label("help", systemImage: "keyboard.macwindow")
}
省略And that's it! This should work now.
If what you're actually after is expanding multiple pieces of info in a sidebar when clicked, check out Apple's official session on the topic — it's explained clearly with sample code:
https://developer.apple.com/jp/videos/play/wwdc2022/10061/