Building views with HStack, VStack, ZStack

Published by @SoNiceInfo at 6/25/2020


Stack is avaliable to display elements.

How to Use Stack

There are three types of Stack and you need to distinguish between them.

  • HStack left and right.
  • VStack up and down.
  • ZStack back and front.

Stack conforms to the View protocol, so you can change the background color, padding and so on with modifiers.
In the example below, the map is aligned vertically and the text is aligned horizontally.

VStack to put the map and text above and below. (Red box)
Please see how to Display Map to create map view.

//
//  ContentView.swift
//

import SwiftUI
import MapKit

struct ContentView: View {
    var body: some View {
        VStack() {
            MapView()
                .edgesIgnoringSafeArea(.all)
            HStack {
                Text("Tokyo")
                    .font(.largeTitle)
                Spacer()
                Text("Tokyo Tower")
            }.padding()
        }
    }
}

struct MapView: UIViewRepresentable {
    func makeUIView(context: Context) -> MKMapView {
        MKMapView(frame: .zero)
        
    }

    func updateUIView(_ uiView: MKMapView, context: Context) {
        let coordinate = CLLocationCoordinate2D(
            latitude: 35.655164046, longitude: 139.740663704)
        let span = MKCoordinateSpan(latitudeDelta: 0.1, longitudeDelta: 0.1)
        let region = MKCoordinateRegion(center: coordinate, span: span)
        uiView.setRegion(region, animated: true)
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}
Display Map and Text using VStack and HStack

References

HStack — SwiftUI Tutorials | Apple Developer Documentation
VStack — SwiftUI Tutorials | Apple Developer Documentation
ZStack — SwiftUI Tutorials | Apple Developer Documentation

    I released iOS App!

    ToDo App

    Visualize Activity, Data sharing with iCloud, Dark mode supported.

    リリースしたToDoアプリのスクリーンショット

    IP Address bookmark.

    Check and bookamrk IP address of all interfaces with geolocation.

    リリースしたIPアドレス保存アプリのスクリーンショット