8

iOS开发 - 在SwiftUI中显示模态视图

 3 years ago
source link: https://www.cnblogs.com/GarveyCalvin/p/swiftui-modal-sheet.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

在SwiftUI中显示模态视图

这里教大家如何弹出一个简单的模态视图。分别有两个页面,ContentView和GCPresentedView,以下对应简称为A和B。我们要做的是在A视图中点击按钮跳转到B视图,然后再从B视图点击按钮返回到A视图。

在A视图中创建按钮和模态视图代码

struct ContentView: View {
    @State var isPresented = false
    
    var body: some View {
        Button(action: {
            self.isPresented = true
        }, label: {
            Text("Present Modally")
        })
        .sheet(isPresented: $isPresented) {
            GCPresentedView()
        }
    }
}

使用@State对属性进行修饰,在 SwiftUI 内部会自动转换为一对getter,setter,对这个属性进行赋值时会触发视图更新。

$isPresented能够将值引用(引用方法是在值前方加一个$符号),当引用的值发生改变时,这个改变会向外传递。

.sheet方法用于弹出一个模态视图,在SwiftUI中的定义为。

public func sheet<Content>(isPresented: Binding<Bool>, onDismiss: (() -> Void)? = nil, @ViewBuilder content: @escaping () -> Content) -> some View where Content : View

在B视图中创建按钮和关闭模态视图代码

struct GCPresentedView: View {
    @Environment(\.presentationMode) var mode
    
    var body: some View {
        Button(action: {
            self.mode.wrappedValue.dismiss()
        }, label: {
            Text("Dismiss")
        })
    }
}

@Environment获取环境变量presentationMode,我们可以通过这个变量调用wrappedValue.dismiss()可以关闭模态视图。

直接在 Xcode 运行预览

使用 SwiftUI 框架处理界面方便很多,不用太多的定义,我们只需要将界面进行描述出来就可以了。这个教程示例中使用到了 Button 和 Text 控件,也用到了@State, Binding, @Environment 技术点。教程很简单,放上来大家一起学习,教程里的代码已放在了GitHub上面,点击这里获取代码

博文作者:GarveyCalvin
博文出处:http://www.cnblogs.com/GarveyCalvin/
本文版权归作者和博客园共有,欢迎转载,但须保留此段声明,并给出原文链接,谢谢合作!


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK