How To Easily Pass Data Between Two Views In SwiftUI

In this 5 minutes article, learn how to pass data between two views effortlessly just by leveraging the @State property wrapper.

Create a new SwiftUI project and select the ContentView.swift file to open it in the editor.

The screen will have a label displaying the selected value, along with a button that opens a list of items for selection.

How To Easily Pass Data Between Two Views In SwiftUI

Declare the following variables:

@State private var selectedItem: String = "-"
@State private var isPresented = false
private var items = ["apples", "pears", "bananas", "pineapples"]

The selectedItem and isPresenting variables are annotated with @State to control the changes of their values and update the part of the view that depends on their values.

Next, replace the content of the body content to the following:

VStack {
  HStack {
      Text("Selected item:")
      Text(selectedItem)
  }
  Spacer().frame(maxHeight: 20.0)
  Button("Show the list"){
      isPresented = true
  }
}
.fullScreenCover(isPresented: $isPresented) {
  List(items, id: \.self){item in
      Text(item).onTapGesture {
          selectedItem = item
          didDismiss()
      }
  }
}

The code above adds some UI elements and align them all in a vertical and horizontal stack views.

Once the button is clicked, the isPresented toggle will be assigned to true which will trigger the fullScreenCover method (that is listening to the isPresented flag) and present the List modally on the screen.

Once an item is chosen from the list, the value of selectedItem will update to correspond with the chosen item, which will consequently affect any UI element that depends on it, such as the text displayed on the screen. It will then call the didDismiss method to dismiss the list and move us back to the main screen.

private func didDismiss() {
   isPresented = false
}

Just like displaying the list, dismissing it is as simple as assigning false to the property that the fullScreenCover method is monitoring, in this case isPresented, to false.

That’s it, run the project and see how the text on the main screen reflects each time the selected item from the list.

References: https://developer.apple.com/documentation/swiftui/view/fullscreencover(ispresented:ondismiss:content:)

Thanks for reading – see you in the next digest!


Discover more from SweetTutos

Subscribe to get the latest posts sent to your email.

Malek
Software craftsman with extensive experience in iOS and web development.