Stephen.W
Stephen.W

Reputation: 2146

How to add padding outside border?

In CSS there is padding and margin. The former adds empty spaces inside border, and the latter adds spaces outside. Currently I am learning SwiftUI and I found the .padding modifier, which is equivalent to CSS's padding property, but I cannot find margin's equivalent.

Does it exist or do I have to create a wrapper view to achieve this goal?

Upvotes: 2

Views: 2319

Answers (1)

ScottM
ScottM

Reputation: 10512

SwiftUI's layout modifiers can be a bit confusing if you're coming from HTML and CSS.

Where CSS has a huge list of properties to choose from, SwiftUI tries to keep things simpler. To do that, it takes advantage of the ability to "chain" modifiers together.

For example, if you had a rectangle that needs internal padding of 8 pixels, a border of 1 pixel width and external margins of 10 pixels, you might express it in CSS like this:

.my-rectangle {
  padding: 8px;
  margin: 10px;
  border: 1px solid red;
}

And in CSS it doesn't matter what order those properties occur within the double braces; each has a specific meaning and is applied in the same way, even if the border property is at the end or the beginning.

In SwiftUI, though, styling is done by applying a modifier to a View, giving you a new view with the modification applied. You can then apply another modifier to that, and another, and so on. And because each modifier is adapting what has gone before, the order is very important.

So if we have a view to which we need to add the same spacing as the example above, we'd structure it something like:

MyView()
  .padding(8) // <-- internal padding
  .border(Color.red, width: 1) <<-- apply the border
  .padding(10) // <-- apply more padding outside the border

Building views up gradually like this is what allows SwiftUI to keep the number of modifiers you need for most views reasonably small and focussed.

As you start building up more complicated views, you'll come across stacks and grids, which also have a concept of spacing between children. Depending on your design, it might be more useful to think about using spacing instead of external padding, especially if you start breaking your design up into reusable components.

But thinking about applying changes in a sequence, instead of all at once like CSS, is the key to constructing great SwiftUI views.

Upvotes: 9

Related Questions