SwiftUI + SegmentedPicker

SwiftUI | Create a Picker With SegmentedPickerStyle

Let’s create a Picker in SwiftUI that will switch views every time the user selects one. Using SwiftUI 2.0 & Xcode 12.

Sullivan De Carli
Swift Productions

--

SwiftUI logo with an iPhone displaying a SwiftUI picker
From the author

Difficulty: Beginner | Easy | Normal | Challenging

Environment : Xcode 12 & SwiftUI

Introduction

In this tutorial, I am going to show you how to implement a Picker with a SegmentedPickerStyle in SwiftUI. We will make the user change View every time he has selected one of the selected pickers. Let’s go!

Create a new Xcode project

Open Xcode > Create a new Xcode project > App template > Call it PickerSwiftUI and select SwiftUI Interface and lifecycle.

Create 3 Views

Go ahead and create 3 new SwiftUI Views and call them the following:

  • bitcoinView
  • ethereumView
  • litecoinView

Then, simply change the text “Hello world” with Bitcoin, Ethereum and Litecoin according to each view. We will present these Views once the user selects it from the Picker.

Let’s Create the Switch Cases

Go back to the ContentView.swift file and copy/paste the following code after the ContentView last closure:

This is a switch case that we are going to use to tell our program to switch between Views based on the user’s selection.

Create the Picker

First, declare the State right over the body variable:

This will give a default selected value. Then, replace the current Text inside the body variable with this code:

This code is creating a NavigationView with a title and presenting a SwiftUI Picker that switches from one View to another based on the selection that we gave with the switch case:

switch selectedToken {

...

}

Run the App 📲

Et voilà! Run your project and switch between cryptocurrencies with the Picker:

Xcode with simulator running

Thanks for reading! I’m always happy to have a chat and collaborate at hello@sullivandecarli.com. Consider subscribing to enjoy unlimited access to my articles and all of Medium through my referral link.

--

--

Sullivan De Carli
Swift Productions

Consultant in iOS Dev at Deloitte. I write about Design & App development. Let’s have a chat at hello@sullivandecarli.com