SwiftUI 跳转到新页面(NavigationLink、fullScreenCover、Link)

前言

xcode 13.3
iOS 15.2

一、 push跳转

添加跳转时间,首先你要在 NavigationView 中包含的代码,只要在vc的body中,把代码放到 NavigationView 就可以了

1、button 跳转(此处是转化成 Text、Image)

文字button

Button("登录/注册") {
    
     //文字
    print("登录/注册")		//点击事件
}

添加跳转事件,YLMySetting是我的要跳转的页面,destination下只要是一个 View就可以跳转,你也可以写一个Text("???")
此处是把纯文字的Button转化为Text再添加的跳转事件

NavigationLink {
    
    
    YLMySetting() //此处为跳转时间,只要是一个view可以跳转过去
} label: {
    
    
    Text("登录/注册")
}

图片button
此处是把纯图片的Button转化为Image再添加的跳转事件

Button {
    
    
    print("setting") //点击事件
} label: {
    
    
    Image("mine_set") //图片 
}

添加跳转事件

NavigationLink {
    
    
    YLMySetting()
} label: {
    
    
    Image("mine_set") 
}

2、List 中row 点击跳转

这块苹果的官方文档中、demo中都有详细说明

NavigationLink {
    
    
    YLMySetting()
} label: {
    
    
    YLMineRow(model: models[index]) //此处为row展示
}

3 push 自定义返回

@Environment(\.presentationMode) var presentationMode: Binding<PresentationMode>

在Button按钮点击事件或者tap中添加 presentationMode.wrappedValue.dismiss() 返回上一页

    var body: some View {
        Button(action: {
            presentationMode.wrappedValue.dismiss()
        }, label: {
            Text("返回")
        })
    }

二、presented跳转

1、要跳转的页面设置

给定一个为false的监控值

    @State var settingPagePresented: Bool = false

给Text添加单击手势,设置监控值跳转

Text("设置") 
    .fullScreenCover(isPresented: $settingPagePresented, content: {
    
    
        YLMySetting(settingPagePresented: $settingPagePresented)
    }).onTapGesture {
    
    
        settingPagePresented = true
    }

2、跳转到的页面

添加绑定状态

    @Binding var settingPagePresented: Bool

添加返回按钮,点击返回上一页

NavigationView {
    
    
    Text("hello world")
    .navigationTitle("设置")
    .navigationBarItems(leading: Button(action: {
    
    
        settingPagePresented = false
    }, label: {
    
    
        Image("icon_back")
    }))
    .navigationBarTitleDisplayMode(.inline)
}

三、跳转到 Safari 浏览器

使用 Link 可以跳转到 Safari浏览器,不过链接要添加上http,否则跳转不了

Link(destination: URL(string: "https://www.baidu.com")!) {
    
    
    Text("百度搜索")
}

总结

1、跳转方法,必须写在NavigationView 中
2、无论是button还是 Text 或者Image,添加跳转,都要把代码放到label中
3、button点击事件中,没能成功添加跳转事件、此处我都是把button 转化为Text 或者Image,有大佬知道怎么添加,请在评论区留言,非常感谢

猜你喜欢

转载自blog.csdn.net/u014651417/article/details/123522914