iOS开发实战:从入门到精通SwiftUI

Viewed 0

iOS 开发实战:从入门到精通 SwiftUI

SwiftUI 是 Apple 推出的声明式 UI 框架,让 iOS 开发变得更加简洁高效。

项目架构

以下是一个典型的 SwiftUI 应用项目架构图:

┌─────────────────────────────────────────────────────┐
│                    App Entry                         │
│                   (@main App)                        │
├─────────────────────────────────────────────────────┤
│              Scene / WindowGroup                     │
├───────────┬───────────┬───────────┬─────────────────┤
│   Views   │ ViewModels│  Models   │   Services      │
├───────────┴───────────┴───────────┴─────────────────┤
│              Data Layer (Core Data / SwiftData)      │
├─────────────────────────────────────────────────────┤
│              Network Layer (URLSession / Alamofire)  │
└─────────────────────────────────────────────────────┘

SwiftUI 基础视图

创建主视图

import SwiftUI

struct ContentView: View {
    @State private var username = ""
    @State private var isLoggedIn = false

    var body: some View {
        NavigationStack {
            VStack(spacing: 20) {
                TextField("用户名", text: $username)
                    .textFieldStyle(.roundedBorder)
                    .padding(.horizontal)

                Button("登录") {
                    performLogin()
                }
                .buttonStyle(.borderedProminent)
            }
            .navigationTitle("欢迎")
        }
    }

    private func performLogin() {
        isLoggedIn = true
    }
}

MVVM 架构

ViewModel 实现

import Foundation
import Combine

@MainActor
class UserViewModel: ObservableObject {
    @Published var users: [User] = []
    @Published var isLoading = false
    @Published var errorMessage: String?

    private let userService: UserServiceProtocol

    init(userService: UserServiceProtocol = UserService()) {
        self.userService = userService
    }

    func fetchUsers() async {
        isLoading = true
        defer { isLoading = false }

        do {
            users = try await userService.getUsers()
        } catch {
            errorMessage = error.localizedDescription
        }
    }
}

在视图中使用

struct UserListView: View {
    @StateObject private var viewModel = UserViewModel()

    var body: some View {
        List(viewModel.users) { user in
            UserRowView(user: user)
        }
        .overlay {
            if viewModel.isLoading {
                ProgressView()
            }
        }
        .task {
            await viewModel.fetchUsers()
        }
    }
}

网络请求

使用 async/await

protocol UserServiceProtocol {
    func getUsers() async throws -> [User]
}

class UserService: UserServiceProtocol {
    private let baseURL = "https://api.example.com"

    func getUsers() async throws -> [User] {
        guard let url = URL(string: "\(baseURL)/users") else {
            throw NetworkError.invalidURL
        }

        let (data, response) = try await URLSession.shared.data(from: url)

        guard let httpResponse = response as? HTTPURLResponse,
              httpResponse.statusCode == 200 else {
            throw NetworkError.invalidResponse
        }

        return try JSONDecoder().decode([User].self, from: data)
    }
}

SwiftData 数据持久化

定义模型

import SwiftData

@Model
class Task {
    var title: String
    var isCompleted: Bool
    var createdAt: Date

    init(title: String, isCompleted: Bool = false) {
        self.title = title
        self.isCompleted = isCompleted
        self.createdAt = Date()
    }
}

配置 App

@main
struct MyApp: App {
    var body: some Scene {
        WindowGroup {
            ContentView()
        }
        .modelContainer(for: Task.self)
    }
}

自定义组件

可复用按钮

struct PrimaryButton: View {
    let title: String
    let action: () -> Void

    var body: some View {
        Button(action: action) {
            Text(title)
                .font(.headline)
                .foregroundColor(.white)
                .frame(maxWidth: .infinity)
                .padding()
                .background(Color.blue)
                .cornerRadius(12)
        }
    }
}

常用技术对比

功能 推荐方案 备选方案
UI 框架 SwiftUI UIKit
数据持久化 SwiftData Core Data, Realm
网络请求 URLSession Alamofire
状态管理 @Observable Combine
依赖注入 Environment Swinject
单元测试 XCTest Quick/Nimble

总结

SwiftUI 结合 Swift Concurrency 和 SwiftData,让 iOS 开发更加现代化。建议从 MVVM 架构起步,逐步掌握 Combine、async/await 等核心技术。

0 Answers