Using SwiftUI to build up the visual elements is just like using legos to create something new. As with any new toy we need to understand how to use it. There are four main concepts you’ll need to know.
Seeing what your making, Previews
The first concept is Previews. They allow you to see what your code will look like in real-time. It’s a great way to quickly make changes and see the effects of them without having to build and deploy the entire app. You can also use previews to test for different device sizes or orientations.
Building Blocks, View elements
View elements are the blocks themself, the main ones are Text, Image are Shape. Most of the time these will be sufficient. But you can build more complex views by building custom views that combine elements.
Fine tuning the blocks, Modifiers
Modifiers are used to fine-tune the blocks that make up your UI. They are a bit like CSS classes in that they help you adjust things like font size, spacing, and color. They can also be used to add animation or other effects to your UI elements.
Arranging the blocks, Containers
Containers are used to arrange your UI elements in a specific way. The most commonly used ones are:
- HStack, arranges elements horizontally
- VStack, arranges elements vertically
- ZStack, arranges elements on top of each other
- Grid, arranges elements in a grid pattern
- List, arranges elements in a scrolling list.
The containers act as “parents” for other UI elements and help organize them on the screen. For example, a Stack container will arrange its child elements vertically or horizontally depending on your preference. Other containers such as Lists or Grids can be used for more complex arrangements of UI elements where each element has its own size or position relative to its siblings. This makes arranging your UI incredibly easy and helps keep your code clean and organized.
Cleaning up view code, Subviews
Subviews allow you to create reusable building blocks of code that can be used throughout an app rather than having one giant view class with all the code in it. This helps keep your code organized and easier to read and maintain over time as you’ll have smaller chunks of focused logic instead of one large block of unrelated logic scattered throughout a single file.
With these four concepts in mind, you should be able to start creating amazing user interfaces with SwiftUI!