传统的NavigationStack和NavigationLink是不是感觉还挺复杂的,而且想做一个简单的页面跳转,在子视图里面还没有自定义的返回功能,还要找很多繁琐的方法来实现子页面返回到父页面,今天就用最简单的方式,实现一个超级简单的页面跳转,只需要有Binding的知识就可以了。
父级页面
在父级页面中设置一个变量showDetail,用来控制显示子页面还是父页面,并使用if else实现页面切换,源代码如下:
//
// HomeView.swift
// SwiftBook
//
// Created by song on 2024/7/11.
//
import SwiftUI
struct HomeView: View {
// 是否显示子页面
@State var showDetail = true
var body: some View {
Group {
// 主视图内容
if showDetail {
Color.blue
.overlay(content: {
Text("这是父级页面")
.foregroundStyle(.white)
.font(/*@START_MENU_TOKEN@*/ .title/*@END_MENU_TOKEN@*/)
.fontWeight(/*@START_MENU_TOKEN@*/ .bold/*@END_MENU_TOKEN@*/)
})
.ignoresSafeArea()
.onTapGesture {
showDetail.toggle()
}
} else {
// 子视图内容
BorderTest(show: $showDetail)
}
}
}
}
#Preview {
HomeView()
}
子页面
在子页面中配置一个@Binding变量,用于接收父级页面传递过来的值,并通过点击返回按钮跳转到原来的页面,源代码:
//
// BorderTest.swift
// SwiftBook
//
// Created by Song on 2024/7/7.
//
import SwiftUI
struct BorderTest: View {
@Binding var show: Bool
var body: some View {
VStack {
HStack {
Image(systemName: "chevron.left")
.font(.system(size: 24)).onTapGesture {
show.toggle()
}
Image("xigua")
.resizable()
.frame(width: 50, height: 50)
.mask(Circle())
Text("1024小神")
Spacer()
Button(action: {}, label: {
Text("关注")
.padding(.horizontal)
.padding(.vertical, 4)
.foregroundColor(.red)
.overlay {
RoundedRectangle(cornerRadius: 20).stroke(.red, lineWidth: 1)
}
})
Button(action: {}, label: {
Image(systemName: "square.and.arrow.up.fill")
.foregroundColor(.black)
})
}.padding(.horizontal)
ScrollView {
ForEach(0 ..< 10) { _ in
Text("1024小神详情页面")
.padding(30)
}
}
}
}
}
#Preview {
BorderTest(show: .constant(false))
}
动画效果
要想添加页面跳转的过度效果,可以使用withAnimation添加动画:
.onTapGesture {
withAnimation(.easeIn) {
showDetail.toggle()
}
}
加上动画后的效果: