Swift中点击按钮后切换视图的实现方法咨询
解决方案
你的实现思路没问题,只是缺了SwiftUI中正确的导航状态管理逻辑。下面给你三种无需Storyboard的视图切换方案,按需选择:
方案1:使用NavigationStack(iOS16+ 推荐)
这是苹果官方推荐的现代层级导航方案,适合常规页面跳转:
修改EnterOptions视图
struct EnterOptions: View { // 管理导航页面栈的路径变量 @State private var navigationPath = NavigationPath() var body: some View { NavigationStack(path: $navigationPath) { VStack { Button(action: { // 将目标页面加入导航路径,触发跳转 navigationPath.append("auth") }) { Text("SIGN UP") .frame(maxWidth: 300) .frame(maxHeight: .greatestFiniteMagnitude) .font(.largeTitle) .fontWeight(.heavy) } } // 根据路径标识匹配对应的目标视图 .navigationDestination(for: String.self) { value in if value == "auth" { makeM() } } } } }
方案2:使用Sheet模态弹窗
如果希望以弹窗形式展示登录注册页面,用这种方式:
修改EnterOptions视图
struct EnterOptions: View { // 控制弹窗的显示/隐藏状态 @State private var showAuthSheet = false var body: some View { VStack { Button(action: { // 触发弹窗显示 showAuthSheet = true }) { Text("SIGN UP") .frame(maxWidth: 300) .frame(maxHeight: .greatestFiniteMagnitude) .font(.largeTitle) .fontWeight(.heavy) } } // 绑定弹窗状态和目标视图 .sheet(isPresented: $showAuthSheet) { makeM() } } }
方案3:全屏视图替换
如果需要直接替换当前页面(无导航返回按钮),可以用状态变量控制视图切换:
修改EnterOptions视图
struct EnterOptions: View { // 控制当前显示的视图类型 @State private var showAuthView = false var body: some View { if showAuthView { makeM() } else { VStack { Button(action: { // 切换到登录注册视图 showAuthView = true }) { Text("SIGN UP") .frame(maxWidth: 300) .frame(maxHeight: .greatestFiniteMagnitude) .font(.largeTitle) .fontWeight(.heavy) } } } } }
额外提醒
Swift命名规范中结构体名称需用大驼峰格式,建议把makeM改成AuthView或MakeM,提升代码可读性。
内容的提问来源于stack exchange,提问作者J. Fern
相关产品推荐
相关产品推荐

