You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

macOS SwiftUI:如何用按钮设置可拖拽调整的窗口宽度

在macOS SwiftUI中实现可拖拽调整+预设尺寸的窗口宽度

问题分析

你的代码中,ContentView使用.frame(width: width)固定了内容宽度,导致windowResizability(.contentSize)无法生效,窗口无法通过拖拽调整大小。要同时实现拖拽调整和预设尺寸,需要调整内容约束并直接操作窗口实例。

修改方案

  1. 移除固定宽度约束:让内容自适应窗口大小,保留App层级的最小/最大宽度限制,确保拖拽范围合规。
  2. 直接操作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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 07:17:12