Добавление внутренних отступов
Используйте отступы, чтобы создать свободное пространство вокруг содержимого.
«Добавление внутренних отступов» — бесплатный урок SwiftUI Academy на CoddyKit. Это урок 1 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения SwiftUI Academy, и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс SwiftUI Academy содержит 4 уроков всего.
Части этого урока еще не переведены и отображаются на английском.
Why Views Feel Cramped
By default a SwiftUI view sits flush against its neighbors and the screen edge. Padding is the breathing room you add so content never feels squeezed.
Meet the padding Modifier
The padding modifier adds space on the outside of a view. Attach it like any other modifier and SwiftUI grows the view's footprint to make room.
Text("Hello")
.padding()The Default Amount
Calling padding() with no value uses a system default that adapts to the platform, usually around 16 points. It is a safe, consistent starting point.
Setting an Exact Amount
Pass a number to control the gap precisely. Here padding(40) adds 40 points of space on every side of the text.
Text("Spaced")
.padding(40)Padding One Edge
You can target a single edge instead of all four. This adds 30 points only on top, leaving the other sides untouched.
Text("Top gap")
.padding(.top, 30)Horizontal and Vertical
The .horizontal and .vertical edge sets are handy shortcuts. This pads the left and right sides at once with one clean call.
Text("Sides")
.padding(.horizontal, 24)Combining Edge Sets
Stack two padding calls to mix amounts per direction. Here the view gets wide horizontal margins and a smaller vertical gap.
Text("Mixed")
.padding(.horizontal, 32)
.padding(.vertical, 8)Order Matters
Modifiers apply outward in order, so where you place padding changes the result. Padding before a background pushes the color outward with the content.
Text("Hi")
.padding()
.background(.yellow)Padding Then Background
Swap the order and the difference is clear: a background applied first, then padding, leaves the color tight to the text with empty space around it.
Text("Hi")
.background(.yellow)
.padding()Padding on Containers
Padding works on stacks and any view, not just text. Wrap a VStack and pad it to push the whole group inward from the screen edges.
VStack {
Text("Line one")
Text("Line two")
}
.padding()Padding vs Margins
SwiftUI has no separate margin concept. Padding is your single tool for spacing, and chaining it gives you full control over every edge.
Quick Check
Test your grip on the padding modifier.
Recap
Nice work! You learned that padding adds breathing room outside a view, with defaults, exact amounts, specific edges, and an order that shapes backgrounds.
Часто задаваемые вопросы
Урок «Добавление внутренних отступов» бесплатный?
Да — полный текст урока «Добавление внутренних отступов» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс SwiftUI Academy, подпишись на CoddyKit PRO. Курс SwiftUI Academy содержит 4 уроков всего.
Чему я научусь в уроке «Добавление внутренних отступов»?
Используйте отступы, чтобы создать свободное пространство вокруг содержимого. Ты практикуешь SwiftUI Academy с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.
Нужен ли мне опыт, чтобы начать SwiftUI Academy?
Предыдущий опыт не требуется. SwiftUI Academy на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 1 из 4.
Сколько времени занимает урок «Добавление внутренних отступов»?
Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.
Можно ли писать и запускать код в этом уроке SwiftUI Academy?
Да. Каждый урок SwiftUI Academy включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.
Все уроки этого курса
- Добавление внутренних отступов
- Изменение размера представлений с помощью frame
- Фоны и радиус скругления
- Spacer и приоритет компоновки