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

使用Xcode 14开发macOS 10.15 SwiftUI应用:报错与配置求助

适配macOS 10.15的SwiftUI项目配置方案

1. 换回传统AppKit生命周期(替代macOS11+的@main App协议)

Xcode14默认的SwiftUI模板用的是macOS11才支持的新App生命周期,这就是你报错的核心原因,得改成旧的AppDelegate方式:

  • 新建两个文件:AppDelegate.swift和MainWindowController.swift(后者可选,看你要不要精细控制窗口)
  • 把以下代码写入AppDelegate.swift:
import Cocoa
import SwiftUI

@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
    var window: NSWindow!

    func applicationDidFinishLaunching(_ aNotification: Notification) {
        // 初始化你的SwiftUI根视图
        let contentView = ContentView()

        // 创建窗口并设置样式
        window = NSWindow(
            contentRect: NSRect(x: 0, y: 0, width: 480, height: 300),
            styleMask: [.titled, .closable, .miniaturizable, .resizable, .fullSizeContentView],
            backing: .buffered, defer: false)
        window.center()
        window.setFrameAutosaveName("Main Window")
        // 把SwiftUI视图嵌入到AppKit的NSHostingView里
        window.contentView = NSHostingView(rootView: contentView)
        window.makeKeyAndOrderFront(nil)
    }

    func applicationWillTerminate(_ aNotification: Notification) {
        // 这里放程序退出时的清理代码
    }
}
  • 如果需要MainWindowController.swift,可以用这段代码:
import Cocoa
import SwiftUI

class MainWindowController: NSWindowController {
    convenience init() {
        let contentView = ContentView()
        let window = NSWindow(
            contentRect: NSRect(x: 0, y: 0, width: 480, height: 300),
            styleMask: [.titled, .closable, .miniaturizable, .resizable, .fullSizeContentView],
            backing: .buffered, defer: false)
        window.contentView = NSHostingView(rootView: contentView)
        self.init(window: window)
        window.center()
        window.setFrameAutosaveName("Main Window")
    }
}
  • 最后删掉原来那个带@main的App结构体文件(比如叫MyApp.swift),或者把@main标记删掉改成普通结构体——现在AppDelegate是程序入口了。

2. 处理API兼容性

SwiftUI本身在macOS10.15上可用,但WindowGroup、Scene这些都是macOS11+专属的,绝对不能用。另外写代码时碰到不确定的API,要用if #available做版本判断,比如:

struct ContentView: View {
    var body: some View {
        Text("Hello, World!")
            .padding()
            .font(
                #available(macOS 11.0, *)
                ? .title
                : .system(size: 20)
            )
    }
}

3. 项目配置收尾

  • 确认项目Target的General标签里,Deployment Target设为macOS 10.15
  • 到Build Settings里,把Swift Language Version改成Swift 5.x(Xcode12+的Swift版本都支持)

关于旧版Xcode模板的获取

不需要单独下载模板,直接安装Xcode12或Xcode13就行——这两个版本的默认SwiftUI模板是适配macOS10.15的,新建项目时选macOS的App模板,再选SwiftUI界面,自动会生成带AppDelegate的项目结构,刚好符合你的需求。

你的电脑能打开旧版Xcode,直接去Apple开发者中心的下载页面找对应版本安装即可(官方渠道最稳妥)。


内容的提问来源于stack exchange,提问作者Pastor J.G Seigle

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 01:27:42