Sunday, June 23, 2019

How to create horizontal and vertical stack views in SwiftUI?


Project files : https://github.com/EdyLucky/HorVerStacks
Open Xcode and either click Create a new Xcode project in Xcode’s startup window, or choose File > New > Project.
In the template selector, select iOS as the platform, select the Single View Apptemplate, and then click Next.


Enter “HorVerStacks” as the Product Name, select the Use SwiftUI checkbox, and click Next. Choose a location to save the project on your Mac.


In Canvas on the right click Resume to display the preview. If the canvas is hidden select Editor > Editor and Canvas to show it.


After resume your screen should look like this:




To customize the Text view select Command+click and from the popover choose Inspect. From the next popover any modification can be done to the Text view. One of the great part of SwiftUI is, as you change anything in the canvas the code part is automatically modified by adding relevant piece of code.




















Change the text to Hello SwiftUi , Font to Headline and Color to Red as shown below on the left and the code will be automatically updated like below on the right.



To create Vertical stack for the view that we modified, Command+Click and from popover Embed in VStack needs to be chosen. The code will be automatically updated.



We can add new Text view to the stack that we create by clicking the plus button (+) at the top right of the Xcode window and then drag a Text view to the place in your code immediately after the Hello SwiftUI text view and change the text inside the view to “Better apps. Less code.”


The canvas and the code will be like this and that is it, we have created Vertical stack for these two views and you can add as many as views or images inside stack by dragging and dropping them inside Vstack.


Next we will add image and create horizontal stack with current vertical stack view.


Drag drop SwiftUI image to Asset Folder. (Image can be downloaded from resources)


Next in ContentView.swift file Command+Click VStack and select Embed in HStack.














This will add VStack into HStack (Horizontal Stack). Next, Image view will be added to HStack by clicking plus (+) and drag drop Image into beginning of HStack above VStack in ContentView.swift file and change Image Name to SwiftUI inside Image View. And resizable() property and height and width of image should be added to make it more visible. 

No comments:

Post a Comment