MVVM 与 The Composable Architecture(TCA)对比
iOS 领域两种最流行的架构模式正面对决:传统的 MVVM 与 Point-Free 出品的函数式 TCA。该如何选择合适的架构?
Apple 的未来:声明式、响应式、跨平台
15 年久经沙场、强大且成熟的框架
| 分类 | SwiftUI | UIKit |
|---|---|---|
| 性能 | 8/10 | 10/10 |
| 学习难易度 | 8/10 | 5/10 |
| 生态系统 | 8/10 | 9/10 |
| 社区 | 8/10 | 9/10 |
| 就业市场 | 8/10 | 9/10 |
| 面向未来 | 10/10 | 6/10 |
// SwiftUI - 用户资料卡片
import SwiftUI
struct ProfileCard: View {
@StateObject private var viewModel = ProfileViewModel()
@State private var isFollowing = false
var body: some View {
VStack(alignment: .leading, spacing: 16) {
HStack {
AsyncImage(url: viewModel.user.avatarURL) { image in
image.resizable().scaledToFill()
} placeholder: {
ProgressView()
}
.frame(width: 64, height: 64)
.clipShape(Circle())
VStack(alignment: .leading) {
Text(viewModel.user.name)
.font(.headline)
Text(viewModel.user.title)
.font(.subheadline)
.foregroundStyle(.secondary)
}
Spacer()
Button(isFollowing ? "取消关注" : "关注") {
withAnimation(.spring(response: 0.3)) {
isFollowing.toggle()
}
}
.buttonStyle(.bordered)
.tint(isFollowing ? .gray : .blue)
}
}
.padding()
.background(.regularMaterial)
.clipShape(RoundedRectangle(cornerRadius: 16))
}
}// UIKit - 用户资料卡片
import UIKit
class ProfileCardViewController: UIViewController {
private let avatarImageView: UIImageView = {
let iv = UIImageView()
iv.contentMode = .scaleAspectFill
iv.clipsToBounds = true
iv.layer.cornerRadius = 32
iv.translatesAutoresizingMaskIntoConstraints = false
return iv
}()
private let nameLabel: UILabel = {
let label = UILabel()
label.font = .preferredFont(forTextStyle: .headline)
label.translatesAutoresizingMaskIntoConstraints = false
return label
}()
private lazy var followButton: UIButton = {
var config = UIButton.Configuration.bordered()
config.title = "关注"
let btn = UIButton(configuration: config)
btn.addTarget(self, action: #selector(followTapped), for: .touchUpInside)
btn.translatesAutoresizingMaskIntoConstraints = false
return btn
}()
override func viewDidLoad() {
super.viewDidLoad()
setupUI()
loadUserData()
}
private func setupUI() {
view.addSubview(avatarImageView)
view.addSubview(nameLabel)
view.addSubview(followButton)
NSLayoutConstraint.activate([
avatarImageView.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 16),
avatarImageView.centerYAnchor.constraint(equalTo: view.centerYAnchor),
avatarImageView.widthAnchor.constraint(equalToConstant: 64),
avatarImageView.heightAnchor.constraint(equalToConstant: 64)
])
}
@objc private func followTapped() {
UIView.animate(withDuration: 0.3) {
self.followButton.alpha = 0.5
} completion: { _ in
UIView.animate(withDuration: 0.3) { self.followButton.alpha = 1 }
}
}
}截至 2025 年,新项目应优先选择 SwiftUI;Apple 的全部投入都在这个方向上。但如果有复杂的定制需求、需要支持 iOS 13 以下版本或存在庞大的遗留代码库,UIKit 仍然是必需的。理想的做法是:先尝试 SwiftUI,需要时再通过 UIViewRepresentable 嵌入 UIKit 组件。
获取免费咨询可以。通过 UIHostingController 可以把 SwiftUI 视图嵌入 UIKit 中,通过 UIViewRepresentable 可以把 UIKit 视图嵌入 SwiftUI 中。大型项目中混合方案很常见。