macOS SwiftUI:如何用按钮设置可拖拽调整的窗口宽度
在macOS SwiftUI中实现可拖拽调整+预设尺寸的窗口宽度
问题分析
你的代码中,ContentView使用.frame(width: width)固定了内容宽度,导致windowResizability(.contentSize)无法生效,窗口无法通过拖拽调整大小。要同时实现拖拽调整和预设尺寸,需要调整内容约束并直接操作窗口实例。
修改方案
- 移除固定宽度约束:让内容自适应窗口大小,保留App层级的最小/最大宽度限制,确保拖拽范围合规。
- 直接操作NSWindow:点击按钮时获取当前窗口,调用API设置预设宽度,同时监听窗口尺寸变化实时更新显示值。
完整代码
import SwiftUI import AppKit struct ResizeTest: App { var body: some Scene { WindowGroup { ContentView() .frame(minWidth: 200, maxWidth: 1000) .padding(0) } .defaultSize(width: 300, height: 400) .windowResizability(.contentSize) } } struct ContentView: View { @State private var currentWidth: Double = 400.0 var body: some View { VStack(alignment: .center) { Text("width: \(String(format: "%.0f", currentWidth))") .font(.headline) Button("设置宽度为600") { guard let window = NSApplication.shared.keyWindow else { return } let newWidth: Double = 600 let newFrame = NSRect( x: window.frame.origin.x, y: window.frame.origin.y, width: newWidth, height: window.frame.height ) window.setFrame(newFrame, display: true, animate: true) currentWidth = newWidth } .padding() .background(Color.blue) .foregroundColor(.white) .cornerRadius(8) } .frame(maxWidth: .infinity, maxHeight: .infinity) .background(Color.green) .onReceive(NotificationCenter.default.publisher(for: NSWindow.didResizeNotification)) { notification in guard let window = notification.object as? NSWindow, window.isKeyWindow else { return } currentWidth = window.frame.width } } }
效果说明
- 拖拽窗口边缘可自由调整宽度,范围被限制在200-1000之间。
- 点击按钮会平滑将窗口宽度调整为600。
- 顶部文本实时显示当前窗口宽度,无论调整方式是拖拽还是按钮设置。
内容的提问来源于stack exchange,提问作者mica
相关产品推荐
相关产品推荐

