You need to enable JavaScript to run this app. SwiftUI iOS应用运行在Mac时如何允许窗口小于默认iPad等效尺寸
优惠活动
大模型
产品
解决方案
定价
更多

SwiftUI iOS应用运行在Mac时如何允许窗口小于默认iPad等效尺寸

解决方案

你之前将frame修饰符加在ContentView上不生效,是因为这个修饰符仅作用于视图本身的尺寸约束,没有修改Mac端运行时的窗口Scene配置,无法控制窗口的大小限制和默认启动尺寸。你可以按以下方案实现需求:

方案1:适配SwiftUI 4+(iOS 16+/macOS 13+ 及以上版本)

直接在WindowGroup(Scene层级)添加窗口相关修饰符即可:

import SwiftUI

@main
struct MyApp: App {
    @Environment(\.scenePhase) var scenePhase
    @UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
    @StateObject var appState = AppState()

    var body: some Scene {
        WindowGroup {
            ContentView()
                .environmentObject(appState)
                // 这里可以添加根视图的最小尺寸约束
                .frame(minWidth: 320, minHeight: 480)
        }
        // 设置窗口默认启动尺寸,模拟iPhone竖屏大小
        .defaultSize(width: 400, height: 800)
        // 让窗口大小遵循内容约束,支持用户自由调整到最小尺寸
        .windowResizability(.contentSize)
    }
}

方案2:兼容低版本系统(iOS 15及更早版本)

如果需要支持旧系统,可以通过SceneDelegate获取窗口对象直接修改配置:

  1. 新增SceneDelegate并在AppDelegate中注册:
class AppDelegate: NSObject, UIApplicationDelegate {
    func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
        let config = UISceneConfiguration(name: nil, sessionRole: connectingSceneSession.role)
        config.delegateClass = SceneDelegate.self
        return config
    }
}

class SceneDelegate: NSObject, UIWindowSceneDelegate {
    func windowScene(_ windowScene: UIWindowScene, didUpdate previousCoordinateSpace: UICoordinateSpace, interfaceOrientation previousInterfaceOrientation: UIInterfaceOrientation, traitCollection previousTraitCollection: UITraitCollection) {
        #if targetEnvironment(macCatalyst)
        // 配置窗口允许的最小尺寸
        windowScene.sizeRestrictions?.minimumSize = CGSize(width: 320, height: 480)
        // 配置启动默认窗口尺寸
        let defaultSize = CGSize(width: 400, height: 800)
        if windowScene.windows.first?.frame.size != defaultSize {
            windowScene.windows.first?.frame = CGRect(
                origin: windowScene.windows.first?.frame.origin ?? .zero,
                size: defaultSize
            )
        }
        #endif
    }
}
  1. 原有MyApp的代码无需额外添加窗口相关修饰符,保持原有逻辑即可。

内容的提问来源于stack exchange,提问作者Tomáš Kafka

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.08 02:24:01