SwiftUI minimalist tutorial 14: ModalView modal pop-up window usage

Get into the habit of writing together! This is the 14th day of my participation in the "Nuggets Daily New Plan·April Update Challenge", click to view the details of the event .

Foreword:

When I was writing this chapter, I found that it was still an "advanced usage" of this content before, but after thinking about it, I didn't write that in-depth first. I was worried that the content would be too much to expand and it would be difficult to digest, so I only listed the simple usage. method.

In the following chapters, we will consider going deeper and deeper. When we have finished talking about how to use the basic functions of SwiftUI, we will also consider some cases of actual projects, so that SwiftUI enthusiasts can really write projects.

Motto of the day: Work hard and have fun.

In this chapter, you will learn to use modal pop-up windows to complete page jumps and custom returns.

In the previous chapter, we learned to use the NavigationView navigation bar to jump between pages, which is a common way of page jumping.

Another way to open a new page, which is also common in iPhones, is to pop up a new page from the bottom.

230.png

We can see that this page does not completely "enter" a new page, it allows the user to swipe down to close the page, which undoubtedly greatly enhances the user experience.

At this time, the user feels that there is no "interruption" or "interference" in the user's operation, and what the user wants to do is completed.

This chapter will be divided into 3 parts.

1. Page jump based on modal pop-up window;

2. Custom return of modal pop-up window;

3. Alerts warning pop-up window;

Okay, enough said, let's get started.

Part 1: Page Jump Based on Modal Popup

First, let's create a new project and name it SwiftUIModalView.

231.png

Let's try a simple modal popup jump.

For example, we create a button on the first page, when we click the button, a modal popup page opens.

How to create a button, you can learn about the previous article.

The code to create the button is as follows:

//按钮
Button(action: {
    // 点击按钮跳转打开模态弹窗
}) {
    // 按钮样式
    Text("打开模态弹窗")
        .font(.system(size: 14))
        .frame(minWidth: 0, maxWidth: .infinity)
        .padding()
        .foregroundColor(.white)
        .background(Color(red: 51 / 255, green: 51 / 255, blue: 51 / 255))
        .cornerRadius(5)
        .padding(.horizontal, 20)

}
复制代码

232.png

Then, we need to create a new page so that we can click the button from the first page to open the second page in a modal pop-up window.

Here, we create a page called DetailView based on the content of the previous chapter.

In the DetailView, we will put a brief description of the text.

// 详情页
struct DetailView: View {
    var body: some View {
        Text("这是一个新页面")
    }
}
复制代码

233.png

Next, we implement the jump method using the modal pop-up window.

.sheet(isPresented: $showDetailView) { 
    //要跳转的页面
 }
复制代码

The method of modal popup is very simple, using the .sheet modifier.

isPresented是模态弹窗的触发条件,需要用$绑定一个操作,我们通常定义一个布尔值,它的初始状态为false。

@State var showDetailView = false
复制代码

当我们在第一个页面点击按钮时,按钮的操作就把这个布尔值变成true,那么就可以同时触发.sheet打开模态弹窗。

这里我们定义了一个叫做showDetailView的参数,它是bool类型,而且初始值为false。

当我们点击按钮时,showDetailView切换状态。

self.showDetailView.toggle()
复制代码

234.png

我们点击模拟器上的Preview试下效果。

点击按钮后,我们可以看到系统打开了我们定义好的模态弹窗页面DetailView了。

完整代码如下:

import SwiftUI

struct ContentView: View {

    @State var showDetailView = false

    var body: some View {

        // 按钮
        Button(action: {
            // 点击按钮跳转打开模态弹窗
            self.showDetailView.toggle()
        }) {
            // 按钮样式
            Text("打开模态弹窗")
                .font(.system(size: 14))
                .frame(minWidth: 0, maxWidth: .infinity)
                .padding()
                .foregroundColor(.white)
                .background(Color(red: 51 / 255, green: 51 / 255, blue: 51 / 255))
                .cornerRadius(5)
                .padding(.horizontal, 20)
        }
        .sheet(isPresented: $showDetailView) {
            DetailView()
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

// 详情页
struct DetailView: View {
    var body: some View {
        Text("这是一个新页面")
    }
}
复制代码

235.png

第二部分:模态弹窗的自定义返回

在DetailView页面里,我们可以通过向下拖动页面,实现关闭页面的效果。

我们也可以尝试给DetailView加上一个关闭按钮,当我们点击关闭按钮时,也关闭这个页面。

还记得上一章我们学习过的NavigationView导航栏吗?我们可以给DetailView内容加上导航,然后导航右边加一个按钮操作。

// 详情页
struct DetailView: View {

    var body: some View {

        NavigationView {

            //主体内容
            Text("这是一个新页面")
                .navigationBarItems(trailing: Button(action: {
                    // 点击按钮关闭弹窗
                }) {
                    Image(systemName: "chevron.down.circle.fill")
                        .foregroundColor(.gray)
                }
            )
        }
    }
}
复制代码

236.png

好了,我们看到在DetailView导航栏右上角创建了一个新按钮。

那么接下来,我们要实现点击按钮,关闭弹窗。

这里我们有两种方法。

方法1:

和上一章NavigationView导航栏一样,创建一个环境变量:

@Environment(\.presentationMode) var presentationMode
复制代码

然后当我们点击按钮时,调用它的函数方法。

self.presentationMode.wrappedValue.dismiss()
复制代码

点击模拟器的Preview,我们发现实现了点击操作,关闭当前的模态弹窗页面。

完整代码如下:

// 详情页
struct DetailView: View {

    //定义环境变量
    @Environment(\.presentationMode) var presentationMode

    var body: some View {

        NavigationView {

            //主体内容
            Text("这是一个新页面")
                .navigationBarItems(trailing: Button(action: {
                    // 点击按钮关闭弹窗
                    self.presentationMode.wrappedValue.dismiss()
                }) {
                    Image(systemName: "chevron.down.circle.fill")
                        .foregroundColor(.gray)
                }
            )
        }
    }
}
复制代码

237.png

方法2:

也是之前的章节学习过 State状态和Binding绑定的使用。

我们可以在DetailView页面用@Binding绑定第一个页面创建的showDetailView布尔值。

//绑定参数
@Binding var showDetailView: Bool
复制代码

然后在DetailView页面,点击按钮操作时,将showDetailView的值切换。

self.showDetailView.toggle()
复制代码

最后在主页中.sheet跳转的目标页面绑定参数回来。

.sheet(isPresented: $showDetailView) {
    DetailView(showDetailView: $showDetailView)
}
复制代码

这样,我们也可以实现页面的返回操作。

DetailView页面完整代码如下:

// 详情页
struct DetailView: View {

    //绑定参数
    @Binding var showDetailView: Bool

    var body: some View {

        NavigationView {

            //主体内容
            Text("这是一个新页面")
                .navigationBarItems(trailing: Button(action: {
                    // 点击按钮关闭弹窗
                    self.showDetailView.toggle()
                }) {
                    Image(systemName: "chevron.down.circle.fill")
                        .foregroundColor(.gray)
                }
            )
        }
    }
}
复制代码

238.png

那么两种方法有什么不同呢?

第一种方法简单来说,是“撤销”原有的操作。

而第二种绑定的方式,是反向传递参数值给到第一个页面。

Both methods have their own advantages. The advantage of the second method is that if the second page needs to return with the parameter value, then we can return the value of the DetailView to the first page by binding.

Part 3: Alerts Warning Popup

In the modal pop-up window, there is another type called Alerts warning pop-up window, which is also a type of modal pop-up window.

We have also seen it often in the app. When we are sure to pay, or trigger a risky operation, the system will open the Alerts warning pop-up window.

Alerts warning pop-up window is a pop-up window for secondary confirmation. It is often used in scenarios such as system risk reminders and whether to execute it immediately.

239.png

The method of creating a warning popup is the same as creating a general modal popup, but the parameters are different.

.alert(isPresented: $showAlert) {
    //Alerts结构体
}
复制代码

We still use isPresented to trigger, we define the state of a variable showAlert, and the initial state is false.

@State var showAlert = false
复制代码

Unlike creating a standard modal pop-up window, the content in .alert is the Alerts structure, which is a standard warning pop-up window.

We use the Alert structure to create the alert popup.

Alert(title: Text("这是弹窗标题"), message: Text("这是弹窗的内容"), primaryButton: .default(Text("确定")), secondaryButton: .cancel(Text("取消")))
复制代码

Now that you have a basic understanding of the usage of the warning pop-up window, let's try it out.

We changed the text of the DetailView page to "Open Alert Popup" and turned it into a button form.

So that we can click the text button to achieve the effect of opening the warning pop-up window.

//主体内容
    Button(action: {
        // 点击按钮打开警告弹窗

        }) {
            Text("打开警告弹窗")
        }
复制代码

240.png

Then we write the method of the warning pop-up window into the DetailView page, which is similar to the method of .sheet in the home page.

First define a variable showAlert, the initial value is false, when the button is clicked, the state of showAlert switches.

Outside the Text button (note the location), use .alert to create an alert popup, and then fill in the Alerts structure code in the alert popup content.

This completes the creation of the Alerts warning popup.

The complete code of DetailView is as follows:

// 详情页
struct DetailView: View {

    // 绑定参数
    @Binding var showDetailView: Bool
    @State var showAlert = false

    var body: some View {

        NavigationView {

            // 主体内容
            Button(action: {
                // 点击按钮打开警告弹窗
                self.showAlert.toggle()
            }) {
                Text("打开警告弹窗")
            }
            .alert(isPresented: $showAlert) {
                //Alerts结构体
                Alert(title: Text("这是弹窗标题"), message: Text("这是弹窗的内容"), primaryButton: .default(Text("确定")), secondaryButton: .cancel(Text("取消")))
            }
            
            
            .navigationBarItems(trailing: Button(action: {
                // 点击按钮关闭弹窗
                self.showDetailView.toggle()
            }) {
                Image(systemName: "chevron.down.circle.fill")
                    .foregroundColor(.gray)
            }
            )
        }
    }
}
复制代码

241.png

Come and try it!

If this column is helpful to you, please like, comment, and follow~

Guess you like

Origin juejin.im/post/7086249115083866120