Home About Contact

 

How to create a custom popup view with SwiftUI

3 min read

There are a number of situations that your iOS app needs to present the users with custom popup views. For example a popup view with choices of selection (without the need to navigate to another view or view controller) or a popup view that shows some important information to alert the users.

To show a custom popup view in SwiftUI, basically we just need to use ZStack. ZStack lets you lay out views from back to front, i.e layering the views.

In short, simply use a ZStack to stack two layers of views. The main view is at the back and the popup view is at the front. But the popup view will be shown only when a @State variable showPopUp is true.

@State private var showPopUp = false

var body: some View {
  ZStack {
      mainView()            
      if $showPopUp.wrappedValue {                
          popUpView()
      }        
    }
}

In our example here, the mainView() is simply a method that returns some View, with a VStack that contains a Text and a Button when touched will set the showPopUp @State variable to true and trigger the popup.

private func mainView() -> some View {
   VStack (spacing : 20) {
      Text("Click the button below to show choices of fruits")
      
      Button(action: {
          withAnimation(.linear(duration: 1)) {
             self.showPopUp = true
          }      
      },label: {
          Text("Show")
      })
   }.padding()
}

The popUpView() method returns some View, with a VStack that has a Text as the title, a List of fruits and a Button when touched will set showPopUp variable to false and close the popup, as follows:.

private let choices = ["Apple", "Orange", "Papaya", "Grape", "Star Fruit", "Strawberries", "Raspberries", "Blueberries"].sorted()
  
private func popUpView() -> some View { 
   VStack (spacing : 10) {
       Text("Choices Of Fruits").font(Font.custom("Avenir-Black", size: 18.0))
       List(choices, id:\.self) { Text($0) }
       Button(action: {
           withAnimation {
               self.showPopUp = false
            }
        }, label: {
                Text("Close")
        })
    
    }
    .padding()
    .frame(width: 240, height: 300)
    .background(Color.white)
    .cornerRadius(20)
    .shadow(radius: 20 )   
}

Please note that withAnimation is used in the Button’s action, so the popup is shown with some animation instead of popping onto the screen straightaway. The result is shown below:

How to show and close a popup view automatically?

The second example here is to show a popup view automatically after the main view has appeared for some times and make the popup view closes itself automatically after some times.

We basically make use of the onAppear() method of a View in SwiftUI (which is similar to viewDidAppear() method in UIKit), to set the @State showPopUp variable to true and false; for showing and closing the popup automatically.

The code of our mainView() method is as follows, it simply presents a VStack with a Text view telling that a popup view will be shown in 3 seconds. And the onAppear() method of the VStack is which we set the @State showPopUp variable to true after 3 seconds.

private func mainView() -> some View {
   VStack(alignment: .leading, spacing: 5){
      Text ("Great you're here. Have a nice day! A Pop-up will show in 3 seconds")
   }
   .onAppear {
      DispatchQueue.main.asyncAfter(deadline: .now() + 3.0) {
         withAnimation(.linear(duration: 0.5)){
             self.showPopUp = true
         }
      }      
    }
}

The popUpView() method is as follows, which it simply presents a popup with some styles and onAppear() is used to set the @State showPopUp variable back to false after a delay of 3 seconds and with animation.

private func popUpView() -> some View {
  VStack (spacing : 10) {
      ZStack {
         Circle().fill(Color.green)
         .frame(width: 200, height: 200)
        
          Text("Welcome to TechChee.com")
          .foregroundColor(.white)
          .font(Font.custom("Avenir-Black", size: 24.0))
            
      }
  }
  .padding().frame(width: 250, height: 250).background(Color.white)
  .cornerRadius(20).shadow(radius: 20 )
  .onAppear{
      DispatchQueue.main.asyncAfter(deadline: .now() + 3.0) {
          withAnimation(.linear(duration: 0.5)){
              self.showPopUp = false
          }
      }
   }    
}

The result is shown below:

The complete source code can be found on GitHub

Spread the love
Posted on December 13, 2020 By Christopher Chee

One thought on “How to create a custom popup view with SwiftUI”

Please leave us your comments below, if you find any errors or mistakes with this post. Or you have better idea to suggest for better result etc.

Your email address will not be published. Required fields are marked *


Our FB Twitter Our IG Copyright © 2021