swiftui-view-generator
Generate SwiftUI views with proper state management (@State, @Binding, @ObservedObject, @StateObject) and macOS-specific patterns
What this skill does
# swiftui-view-generator
Generate SwiftUI views with proper state management for macOS applications. This skill creates well-structured SwiftUI components using @State, @Binding, @ObservedObject, @StateObject, and @EnvironmentObject property wrappers.
## Capabilities
- Generate SwiftUI views with proper state management
- Create reusable view components
- Set up data flow with Combine
- Implement navigation patterns
- Generate macOS-specific UI elements
- Create preference-based layouts
- Set up environment values
- Generate preview providers
## Input Schema
```json
{
"type": "object",
"properties": {
"projectPath": {
"type": "string",
"description": "Path to the Swift project"
},
"viewName": {
"type": "string",
"description": "Name of the view to generate"
},
"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"]
}
```
## Output Schema
```json
{
"type": "object",
"properties": {
"success": { "type": "boolean" },
"files": {
"type": "array",
"items": {
"type": "object",
"properties": {
"path": { "type": "string" },
"type": { "enum": ["view", "viewmodel", "model"] }
}
}
}
},
"required": ["success"]
}
```
## Generated SwiftUI View Example
```swift
// 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 {
// Sidebar
SidebarView(selection: $viewModel.selectedCategory)
} detail: {
// Detail view
if let category = viewModel.selectedCategory {
CategoryDetailView(category: category)
} else {
Text("Select a category")
.foregroundStyle(.secondary)
}
}
.searchable(text: $searchText, prompt: "Search items...")
.onChange(of: searchText) { _, newValue in
viewModel.search(query: newValue)
}
.toolbar {
ToolbarItemGroup {
Button(action: viewModel.refresh) {
Label("Refresh", systemImage: "arrow.clockwise")
}
Button(action: { isShowingSettings = true }) {
Label("Settings", systemImage: "gear")
}
}
}
.sheet(isPresented: $isShowingSettings) {
SettingsView()
}
.task {
await viewModel.loadData()
}
}
}
// MARK: - Preview
#Preview {
ContentView()
}
#Preview("With Data") {
ContentView()
.environmentObject(PreviewData.sampleViewModel)
}
```
### ViewModel
```swift
// 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) {
// Debounced search implementation
Task {
try? await Task.sleep(nanoseconds: 300_000_000)
// Perform search
}
}
func refresh() {
Task {
await loadData()
}
}
}
```
### Reusable Component
```swift
// 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("Edit") { }
Button("Duplicate") { }
Divider()
Button("Delete", role: .destructive) {
onDelete?()
}
}
}
}
```
### Settings View (macOS)
```swift
// SettingsView.swift
import SwiftUI
struct SettingsView: View {
var body: some View {
TabView {
GeneralSettingsView()
.tabItem {
Label("General", systemImage: "gear")
}
AppearanceSettingsView()
.tabItem {
Label("Appearance", systemImage: "paintpalette")
}
AdvancedSettingsView()
.tabItem {
Label("Advanced", 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("Launch at Login", isOn: $launchAtLogin)
Toggle("Check for Updates Automatically", isOn: $checkForUpdates)
}
.formStyle(.grouped)
.padding()
}
}
```
### List View with Selection
```swift
// 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("Name", value: \.name)
TableColumn("Type", value: \.type)
TableColumn("Modified", value: \.modifiedDate) { item in
Text(item.modifiedDate, style: .date)
}
TableColumn("Size") { 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("Open") { viewModel.open(items) }
Button("Delete", role: .destructive) { viewModel.delete(items) }
} primaryAction: { items in
viewModel.open(items)
}
}
}
```
## State Management Patterns
### @State - Local state
```swift
@State private var isExpanded = false
@State private var selectedTab = 0
```
### @Binding - Related in General
modeling-omnistudio-epc-catalog
IncludedSalesforce Industries CME EPC product-modeling skill for Product2-based catalog creation. Use when creating EPC products, configuring product attributes, building offer bundles with Product Child Items, or reviewing EPC DataPack JSON metadata for product catalog changes. TRIGGER when: user creates or updates Product2 EPC records, AttributeAssignment payloads, AttributeMetadata/AttributeDefaultValues, Offer bundles, or ProductChildItem relationships. DO NOT TRIGGER when: designing OmniScripts/FlexCards/Integration Procedures (use building-omnistudio-omniscript, building-omnistudio-flexcard, or building-omnistudio-integration-procedure), implementing Apex business logic (use generating-apex), or troubleshooting deployment pipelines (use deploying-metadata).
relationship-science-coach
IncludedUse this skill for direct, practical adult relationship coaching: couples conflict, repair, trust, marriage, dating, flirting, attachment patterns, emotional connection, sex, desire differences, eroticism, kink negotiation, affection, love languages, breakups, and long-term passion. Draw on Gottman, EFT and Hold Me Tight, attachment science, modern sex research, Perel, Nagoski, Kerner, Schnarch, Love and Stosny, and flexible love-language tools. Be concrete and low-hedge. Redirect only for imminent danger, abuse, coercive control, minors, non-consent, self-harm, stalking, or medical/legal/psychiatric decisions.
building-sf-integrations
IncludedSalesforce integration architecture and runtime plumbing with 120-point scoring. Use this skill to set up Named Credentials, External Credentials, External Services, REST/SOAP callout patterns, Platform Events, and Change Data Capture. TRIGGER when: user sets up Named Credentials, External Services, REST/SOAP callouts, Platform Events, CDC, or touches .namedCredential-meta.xml files. DO NOT TRIGGER when: Connected App/OAuth config (use configuring-connected-apps), Apex-only logic (use generating-apex), or data import/export (use handling-sf-data).
venue-templates
IncludedAccess comprehensive LaTeX templates, formatting requirements, and submission guidelines for major scientific publication venues (Nature, Science, PLOS, IEEE, ACM), academic conferences (NeurIPS, ICML, CVPR, CHI), research posters, and grant proposals (NSF, NIH, DOE, DARPA). This skill should be used when preparing manuscripts for journal submission, conference papers, research posters, or grant proposals and need venue-specific formatting requirements and templates.
let-fate-decide
IncludedDraws the 12 Houses of the Zodiac Tarot spread to inject entropy into planning when prompts are vague, ambiguous, or casually delegated. Interprets the spread to guide next steps. Use when the user says 'let fate decide', 'YOLO', 'whatever', 'idk', or other nonchalant phrases, makes Yu-Gi-Oh references, or when you are about to arbitrarily pick between multiple reasonable approaches. Prefer over ask-questions-if-underspecified when the user's tone is casual or playful rather than precision-seeking.
net-ops
IncludedCross-platform network troubleshooting (Windows, macOS, Linux) via local or remote shell. Use for: DNS broken, can't resolve hostnames, nslookup/dig works but apps fail, NRPT, WFP, scutil, /etc/resolver, systemd-resolved, /etc/resolv.conf, NetworkManager, VPN DNS leak residue (ProtonVPN/Mullvad/WireGuard/AnyConnect), AV/firewall blocking DNS or DoH, Tailscale DNS interaction, intermittent connectivity, remote diagnostics over SSH.