Xcode Hot Reloading

最近几年很少写原生的iOS程序,写的多的是 React NativeFlutter,他们都支持Hot Reloading, 不用重新运行就能看到最新的UI效果。相比之下Xcode真的逊色很多,最近写SwiftUI尝试了一下Preview 功能,实在是太弱鸡了,Google了一下解决方案,还真有Xcode Hot Reloading。记录一下。

Steps

参考文档

github InjectionIII

github Inject

配置

InjectionIII配置

  • 安装后打开InjectionIII, 在桌面是看不到InjectoinIII窗口的,点击状态栏图标,选择Open Project,选择项目目录
  • 勾选File Watcher选项, 选择的项目会在Open Recent中展示

SwiftUI项目配置

  • 打开工程,选择 File → Swift Packages → Add Package Dependency, 输入Inject查找, 添加package
  • 在工程所有的Target中设置 Other Linker Flag, 添加-Xlinker -interposable

代码设置

  • 导入头文件
  • 添加 @ObservedObject private var iO = Inject.observer 变量
  • 在需要刷新的控件结尾调用.enableInjection()
import SwiftUI
import Inject

struct ContentView: View {
  @ObservedObject private var iO = Inject.observer
  
    var body: some View {
        Text("Hello, !")
            .padding()
            .enableInjection()
    }
}

Debug

  • 运行代码看到以下输出就代表配置成功了
💉 InjectionIII connected /Demo/SwiftUI_Widget/SwiftUI_Widget.xcodeproj
💉 Watching files under /Demo/SwiftUI_Widget
💉 💉 ⚠️ Your project file seems to be in the Desktop or Documents folder and may prevent InjectionIII working as it has special permissions.
  • 修改后Ctrl+S 保存就能看到神奇的刷新效果了
💉 Compiling /Demo/SwiftUI_Widget/SwiftUI_Widget/ContentView.swift
💉 Loading .dylib ...
💉 Loaded .dylib - Ignore any duplicate class warning ⬆️
💉 Interposed 3 function references.
💉 Injected type #1 'SwiftUI_Widget.ContentView'
💉 Injected type #2 'SwiftUI_Widget.ContentView_Previews'
  • 这是SwiftUI的配置过程,其他工程可以参考官方的文档