DEV Community

MZ
MZ

Posted on

SwiftUI Shape vs View

SwiftUI provides a Shape type. This includes Rectangle, Circle etc. Below is the sample code.

var body: some View { VStack { Rectangle() .fill(.red) .frame(width: 200, height: 200) } } 
Enter fullscreen mode Exit fullscreen mode

Right, let's break this down.

With this code, you would actually have a black rectangle that covers the entire screen, except for the safe area and the bottom part of the screen.

var body: some View { VStack { Rectangle() } } 
Enter fullscreen mode Exit fullscreen mode

Why black?

A Shape is just a geometry. A path, if you will. Think of it like an area with nothing inside but an empty space, but it has a boundary. SwiftUI renders a default black "background" so we can actually see there is at least something rendered instead of a transparent rectangle.

Why does it span the entire screen?

A Shape takes after the size or the borders of its parent.

Shape versus View

Technically, a Shape has no "content". It's literally an empty area. SwiftUI then "fills" that empty area with a black "background". I put background in quotes because it's not technically the background, it's the content.

This is where Shape differs from View. A View already has content. It also has a background property. In a sense, a Shape is a more stripped down version of a View.

Technicalities

This also explains why you cannot apply a frame first. You can only apply a frame if it's a View. Shape is not a View. It only turns into a View once you apply the .fill property. It is a requirement to apply the fill to the Shape, in which case, it turns into a ShapeView, which is a subclass of View.

If you ever take away anything, it is that with Shape, you "fill" it first. A View, on the other hand, lets you set the frame right away.

var body: some View { VStack { Rectangle() .fill(.red) // unique to Shape, returns a View .frame(width: 200, height: 200) // you can now apply .frame since it's a View now } } 
Enter fullscreen mode Exit fullscreen mode

To make it clearer, here are the differences between a Shape and a View.

Shape

  • Required to fill the content first. This turns the Shape into a ShapeView, which is a subclass of View
  • You can then frame the View
  • Yes, you can also apply a background. But it does get covered by the fill colour.
var body: some View { VStack { Rectangle() .fill(.red) // unique to Shape, returns a View .frame(width: 200, height: 200) // you can now apply .frame since it's a View now } } 
Enter fullscreen mode Exit fullscreen mode

View

  • No need for content filling. Views already have a default content to display.
  • Frame the view
  • You can apply a background
var body: some View { VStack { View() .frame(width: 200, height: 200) // you can now apply .frame since it's a View now .background(.red) } } 
Enter fullscreen mode Exit fullscreen mode

Top comments (0)