SwiftUI视图生成器Skill swiftui-view-generator

这是一个用于生成macOS应用程序SwiftUI视图的专业工具,专注于状态管理(@State, @Binding, @ObservedObject, @StateObject)和macOS特定模式。该技能能够自动创建结构良好的SwiftUI组件、视图模型和可重用UI元素,支持Combine数据流、导航模式、环境值设置和预览生成。适用于iOS/macOS开发者快速构建现代化Apple平台应用界面。关键词:SwiftUI开发,macOS应用,状态管理,UI组件生成,Apple开发,移动开发,桌面应用,视图模型,Combine框架,Swift编程

移动开发 0 次安装 0 次浏览 更新于 2/25/2026

name: swiftui-view-generator description: 为macOS应用程序生成具有正确状态管理的SwiftUI视图。此技能使用@State、@Binding、@ObservedObject、@StateObject和@EnvironmentObject属性包装器创建结构良好的SwiftUI组件。 allowed-tools: Read, Write, Edit, Bash, Glob, Grep tags: [swiftui, macos, swift, ui, apple]

swiftui-view-generator

为macOS应用程序生成具有正确状态管理的SwiftUI视图。此技能创建结构良好的SwiftUI组件,使用@State、@Binding、@ObservedObject、@StateObject和@EnvironmentObject属性包装器。

能力

  • 生成具有正确状态管理的SwiftUI视图
  • 创建可重用的视图组件
  • 使用Combine设置数据流
  • 实现导航模式
  • 生成macOS特定的UI元素
  • 创建基于偏好的布局
  • 设置环境值
  • 生成预览提供程序

输入模式

{
  "type": "object",
  "properties": {
    "projectPath": {
      "type": "string",
      "description": "Swift项目路径"
    },
    "viewName": {
      "type": "string",
      "description": "要生成的视图名称"
    },
    "viewType": {
      "enum": ["screen", "component", "list", "form", "settings", "sheet"],
      "default": "screen"
    },
    "stateProperties": {
      "type": "array",
      "items": {
        "type": "object",
        "properties": {
          "name": { "type": "string" },
          "type": { "type": "string" },
          "wrapper": { "enum": ["State", "Binding", "ObservedObject", "StateObject", "EnvironmentObject"] }
        }
      }
    },
    "includeViewModel": {
      "type": "boolean",
      "default": true
    },
    "macOSSpecific": {
      "type": "boolean",
      "default": true
    }
  },
  "required": ["projectPath", "viewName"]
}

输出模式

{
  "type": "object",
  "properties": {
    "success": { "type": "boolean" },
    "files": {
      "type": "array",
      "items": {
        "type": "object",
        "properties": {
          "path": { "type": "string" },
          "type": { "enum": ["view", "viewmodel", "model"] }
        }
      }
    }
  },
  "required": ["success"]
}

生成的SwiftUI视图示例

// ContentView.swift
import SwiftUI

struct ContentView: View {
    @StateObject private var viewModel = ContentViewModel()
    @State private var searchText = ""
    @State private var isShowingSettings = false

    var body: some View {
        NavigationSplitView {
            // 侧边栏
            SidebarView(selection: $viewModel.selectedCategory)
        } detail: {
            // 详情视图
            if let category = viewModel.selectedCategory {
                CategoryDetailView(category: category)
            } else {
                Text("选择一个分类")
                    .foregroundStyle(.secondary)
            }
        }
        .searchable(text: $searchText, prompt: "搜索项目...")
        .onChange(of: searchText) { _, newValue in
            viewModel.search(query: newValue)
        }
        .toolbar {
            ToolbarItemGroup {
                Button(action: viewModel.refresh) {
                    Label("刷新", systemImage: "arrow.clockwise")
                }

                Button(action: { isShowingSettings = true }) {
                    Label("设置", systemImage: "gear")
                }
            }
        }
        .sheet(isPresented: $isShowingSettings) {
            SettingsView()
        }
        .task {
            await viewModel.loadData()
        }
    }
}

// MARK: - 预览
#Preview {
    ContentView()
}

#Preview("带数据") {
    ContentView()
        .environmentObject(PreviewData.sampleViewModel)
}

视图模型

// ContentViewModel.swift
import SwiftUI
import Combine

@MainActor
class ContentViewModel: ObservableObject {
    @Published var items: [Item] = []
    @Published var selectedCategory: Category?
    @Published var isLoading = false
    @Published var errorMessage: String?

    private let dataService: DataService
    private var cancellables = Set<AnyCancellable>()

    init(dataService: DataService = .shared) {
        self.dataService = dataService
    }

    func loadData() async {
        isLoading = true
        errorMessage = nil

        do {
            items = try await dataService.fetchItems()
        } catch {
            errorMessage = error.localizedDescription
        }

        isLoading = false
    }

    func search(query: String) {
        // 防抖搜索实现
        Task {
            try? await Task.sleep(nanoseconds: 300_000_000)
            // 执行搜索
        }
    }

    func refresh() {
        Task {
            await loadData()
        }
    }
}

可重用组件

// ItemRowView.swift
import SwiftUI

struct ItemRowView: View {
    let item: Item
    @Binding var isSelected: Bool
    var onDelete: (() -> Void)?

    var body: some View {
        HStack {
            Image(systemName: item.icon)
                .foregroundStyle(item.color)
                .frame(width: 24, height: 24)

            VStack(alignment: .leading, spacing: 4) {
                Text(item.title)
                    .font(.headline)

                Text(item.subtitle)
                    .font(.subheadline)
                    .foregroundStyle(.secondary)
            }

            Spacer()

            if isSelected {
                Image(systemName: "checkmark")
                    .foregroundStyle(.blue)
            }
        }
        .padding(.vertical, 4)
        .contentShape(Rectangle())
        .onTapGesture {
            isSelected.toggle()
        }
        .contextMenu {
            Button("编辑") { }
            Button("复制") { }
            Divider()
            Button("删除", role: .destructive) {
                onDelete?()
            }
        }
    }
}

设置视图 (macOS)

// SettingsView.swift
import SwiftUI

struct SettingsView: View {
    var body: some View {
        TabView {
            GeneralSettingsView()
                .tabItem {
                    Label("通用", systemImage: "gear")
                }

            AppearanceSettingsView()
                .tabItem {
                    Label("外观", systemImage: "paintpalette")
                }

            AdvancedSettingsView()
                .tabItem {
                    Label("高级", systemImage: "slider.horizontal.3")
                }
        }
        .frame(width: 500, height: 400)
    }
}

struct GeneralSettingsView: View {
    @AppStorage("launchAtLogin") private var launchAtLogin = false
    @AppStorage("checkForUpdates") private var checkForUpdates = true

    var body: some View {
        Form {
            Toggle("登录时启动", isOn: $launchAtLogin)
            Toggle("自动检查更新", isOn: $checkForUpdates)
        }
        .formStyle(.grouped)
        .padding()
    }
}

带选择的列表视图

// ItemListView.swift
import SwiftUI

struct ItemListView: View {
    @ObservedObject var viewModel: ItemListViewModel
    @State private var selection: Set<Item.ID> = []
    @State private var sortOrder = [KeyPathComparator(\Item.name)]

    var body: some View {
        Table(viewModel.items, selection: $selection, sortOrder: $sortOrder) {
            TableColumn("名称", value: \.name)
            TableColumn("类型", value: \.type)
            TableColumn("修改时间", value: \.modifiedDate) { item in
                Text(item.modifiedDate, style: .date)
            }
            TableColumn("大小") { item in
                Text(ByteCountFormatter.string(fromByteCount: item.size, countStyle: .file))
            }
            .width(80)
        }
        .onChange(of: sortOrder) { _, newOrder in
            viewModel.sort(by: newOrder)
        }
        .contextMenu(forSelectionType: Item.ID.self) { items in
            Button("打开") { viewModel.open(items) }
            Button("删除", role: .destructive) { viewModel.delete(items) }
        } primaryAction: { items in
            viewModel.open(items)
        }
    }
}

状态管理模式

@State - 本地状态

@State private var isExpanded = false
@State private var selectedTab = 0

@Binding - 来自父视图的双向绑定

@Binding var isPresented: Bool
@Binding var selectedItem: Item?

@StateObject - 拥有的可观察对象

@StateObject private var viewModel = MyViewModel()

@ObservedObject - 传递的可观察对象

@ObservedObject var viewModel: MyViewModel

@EnvironmentObject - 通过环境共享

@EnvironmentObject var settings: AppSettings

@AppStorage - 基于UserDefaults

@AppStorage("username") private var username = ""

最佳实践

  1. 使用@StateObject进行所有权管理:当视图创建对象时
  2. 使用@ObservedObject进行注入:当对象被传入时
  3. 保持视图小巧:提取组件
  4. 使用预览:测试不同状态
  5. 标记异步操作:为ViewModel使用@MainActor
  6. 优雅处理错误:显示用户友好的消息

相关技能

  • macos-entitlements-generator - 应用能力
  • macos-notarization-workflow - 分发
  • xctest-ui-test-generator - UI测试

相关代理

  • swiftui-macos-expert - SwiftUI专业知识
  • desktop-ux-analyst - UX模式