Spacer Sandwish

To organize multiple subviews in limited space, simple adding the views will make the views appear very close to each other because there is no spacing. Adding the spacing between items is by lucky since you never know how much space is required to separate those items evenly. Nevermind that the screen size of each device is different.

A better way is to add Spacer to each item.

HStack {
                ForEach(0..<5) { num in
                    Button {
                    } label: {
                            Image(systemName: tabBarImageNames[num])
                                .font(.system(size: 24))
                                .foregroundColor(num == selectedIndex ? .black : Color(white: 0.8))
                    }

                }
            }

The default alignment is center, so 5 views in centered aligned, and with the default spacing between each other

The default alignment is center, so 5 views in centered aligned, and with the default spacing between each other

By adding a Spacer Before the Image, the HStack now occupy the full space. For the reason that, Spacer will occupy as much space as its parent can provide. In this case the Spacer's parent is HStack, and this HStack can occupy the full width of the screen.

By adding a Spacer Before the Image, the HStack now occupy the full space. For the reason that, Spacer will occupy as much space as its parent can provide. In this case the Spacer's parent is HStack, and this HStack can occupy the full width of the screen.

To think about how multiple Spacer work together. We firstly think of the size of them. Suppose all the icons's width are together 20, and the width of the screen is 100. Then the space left for the Spacer is 80. we have 5 spacer in this case, so the space for each Spacer is 80 / 5 = 16. Because we align our items as: Spacer → First Icon → Spacer → Second Icon → Spacer ... → Last Icon, we will have the fisrt 16 points of space as Spacer, and then the space for the first icon, and so on till the last.

By adding another Spacer after the Image, we will have each 10 Spacer fighting for the 80 points of space, since we have Spacer → First Icon → Spacer → Spacer → Second Icon → Spacer ... till the last, we will have an organized tab bar.

By adding another Spacer after the Image, we will have each 10 Spacer fighting for the 80 points of space, since we have Spacer → First Icon → Spacer → Spacer → Second Icon → Spacer ... till the last, we will have an organized tab bar.

Disappearing Space in VStack

The space between ScrollView and Divider, divider and icon is the result of default spacing in the VStack.