什么是视图?
学习 View 协议和 body 计算属性。
什么是视图? 是 CoddyKit 上的免费 SwiftUI Academy 课时。 这是第 1 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 SwiftUI Academy 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 SwiftUI Academy 课程共包含 4 节课。
本课时的部分内容尚未翻译,以英文显示。
Everything Is a View
In SwiftUI, almost everything you see on screen is a view. Text, images, buttons, and even your whole screen are all views. 📱
The View Protocol
A view is any type that conforms to the View protocol. Conforming means you promise to describe what should appear on screen.
struct ContentView: View {
var body: some View {
Text("Hello!")
}
}Views Are Structs
Most SwiftUI views are simple structs. They are lightweight value types, so SwiftUI can create and discard them cheaply as your UI changes.
The body Requirement
The View protocol has one job for you: provide a body property. It is where you describe the view's content.
struct ContentView: View {
var body: some View {
Text("Welcome")
}
}body Is Computed
The body is a computed property, not stored. SwiftUI reads it whenever it needs to redraw, so it always reflects your latest code.
What some View Means
The return type some View says body returns one specific view type, but you do not have to spell out which. The compiler figures it out.
var body: some View {
Text("Opaque type magic")
}One View, Many Pieces
A single view's body often combines many smaller views. The whole arrangement is still treated as one view from the outside. 🧩
Views Describe, Not Draw
You never paint pixels yourself. A view simply describes what it wants, and SwiftUI decides how to render it efficiently.
Views Are Cheap and Disposable
Because views are value types, SwiftUI recreates them constantly. Do not store heavy work in a view; keep its body fast and simple.
Composing Custom Views
You build your app by writing your own custom views. Each one is a struct conforming to View, just like the built-in ones.
struct GreetingView: View {
var body: some View {
Text("Hi there")
}
}Reusing Your Views
Once you define a view, you can drop it anywhere just by its name. This reuse keeps your UI consistent and your code tidy.
var body: some View {
GreetingView()
}Quick Check
Let's confirm what makes a type a SwiftUI view.
Recap: What Is a View?
A view is a struct that conforms to View and provides a body of type some View. Views describe content, are cheap, and compose into your whole UI. 🎉
常见问题解答
「什么是视图?」课时是免费的吗?
是的 — 「什么是视图?」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 SwiftUI Academy 课程的其余内容,请升级到 CoddyKit PRO。 SwiftUI Academy 课程共包含 4 节课。
「什么是视图?」这节课中我会学到什么?
学习 View 协议和 body 计算属性。 你通过在浏览器中直接运行的动手代码来练习 SwiftUI Academy,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 SwiftUI Academy 需要有经验吗?
无需任何先前经验。CoddyKit 上的 SwiftUI Academy 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 1 节课,共 4 节。
「什么是视图?」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 SwiftUI Academy 课中编写并运行代码吗?
能。每节 SwiftUI Academy 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。