SwiftUI中如何使用NavigationLink跳转到随机视图?
报错原因
你遇到的Type '()' cannot conform to 'View'错误,是因为NavigationLink的destination闭包要求必须返回一个View类型的内容,不能在其中直接执行赋值这类返回Void的操作——你原本想在switch的case里修改valore,这就导致闭包返回的内容不符合要求。
解决方案一:在目标视图出现时更新变量
通过给目标视图添加.onAppear修饰符,在进入跳转后的视图时重新随机化valore,返回原视图后数值会自动更新。
修改后的完整代码:
import SwiftUI struct ContentView: View { @State var valore = Int.random(in: 1...4) var body: some View { NavigationStack { NavigationLink { Group { switch valore { case 1: ContentView1() case 2: ContentView2() case 3: ContentView3() case 4: ContentView4() default: ContentView() } } .onAppear { // 进入目标视图时重新生成随机值 valore = Int.random(in: 1...4) } } label: { Image("Retro") .resizable() .cornerRadius(27.0) .aspectRatio(contentMode: .fit) .padding() } Text("\(valore)") .bold() .font(.title) } } }
解决方案二:用Button结合navigationDestination控制跳转
通过Button触发点击事件,先更新valore再启动导航,这种方式逻辑更直观,点击按钮时直接生成新的随机值并跳转对应视图。
修改后的完整代码:
import SwiftUI struct ContentView: View { @State var valore = Int.random(in: 1...4) @State private var isNavigating = false var body: some View { NavigationStack { Button { // 点击按钮时先更新随机值 valore = Int.random(in: 1...4) // 触发导航 isNavigating = true } label: { Image("Retro") .resizable() .cornerRadius(27.0) .aspectRatio(contentMode: .fit) .padding() } .navigationDestination(isPresented: $isNavigating) { switch valore { case 1: ContentView1() case 2: ContentView2() case 3: ContentView3() case 4: ContentView4() default: ContentView() } } Text("\(valore)") .bold() .font(.title) } } }
两种方案的区别
- 方案一:先根据当前
valore跳转对应视图,进入视图后更新数值,返回原视图时看到新的随机值。 - 方案二:点击按钮时直接更新
valore,再跳转新数值对应的视图,跳转后原视图的数值已经是新值。
内容的提问来源于stack exchange,提问作者manlio_01
相关产品推荐
相关产品推荐

