避免不必要的重绘
限定状态作用域,减少 body 重新计算。
避免不必要的重绘 是 CoddyKit 上的免费 SwiftUI Academy 课时。 这是第 2 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 SwiftUI Academy 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 SwiftUI Academy 课程共包含 4 节课。
本课时的部分内容尚未翻译,以英文显示。
The Cost of Over-Updating
If a tiny change forces a huge view to rebuild, scrolling stutters. The fix is to keep each redraw as small as possible.
State Lives Where It Changes
Put @State in the smallest view that owns it. Then only that little view re-evaluates when the value flips, not its big parent.
struct Counter: View {
@State private var count = 0
}Extract Subviews
Break a large body into smaller subviews. SwiftUI can then diff and skip the pieces whose inputs did not change.
var body: some View {
HeaderView()
FeedView()
}Pass Only What You Need
Hand a subview just the values it reads. The fewer dependencies a view has, the less often it must recompute.
RowView(title: item.title)Watch Observable Reads
With @Observable models, a view updates only for the exact properties it touches. Read just the fields you display.
Avoid Wide State Objects
One giant model read everywhere makes every change ripple outward. Split it so each view depends on a narrow slice of data.
Beware Closures Capturing Self
A closure that reads many properties widens a view's dependencies. Capture only the specific value the action truly needs.
Move Heavy Work Out of body
Never do expensive computing inside body. It runs often, so cache results in state or a model and read the finished value.
Use let for Constants
Mark unchanging inputs as let. Constant properties never trigger updates, signaling clearly that they cannot cause a redraw.
struct Badge: View {
let label: String
}Equatable Views
For costly subviews, make them Equatable so SwiftUI can compare inputs and skip re-evaluation when they match.
ExpensiveView(data: data)
.equatable()Optimize What You Measure
Do not guess. Scope state, extract views, then measure to confirm you actually shrank the redraws that hurt.
Quick Check
Where should you place state to limit redraws?
Recap: Avoiding Redraws
You learned to scope state tightly, extract subviews, pass minimal data, and keep body cheap. Smaller dependencies mean fewer redraws. ⚡
常见问题解答
「避免不必要的重绘」课时是免费的吗?
是的 — 「避免不必要的重绘」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 SwiftUI Academy 课程的其余内容,请升级到 CoddyKit PRO。 SwiftUI Academy 课程共包含 4 节课。
「避免不必要的重绘」这节课中我会学到什么?
限定状态作用域,减少 body 重新计算。 你通过在浏览器中直接运行的动手代码来练习 SwiftUI Academy,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 SwiftUI Academy 需要有经验吗?
无需任何先前经验。CoddyKit 上的 SwiftUI Academy 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 2 节课,共 4 节。
「避免不必要的重绘」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 SwiftUI Academy 课中编写并运行代码吗?
能。每节 SwiftUI Academy 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。