struct RandomizeTab: View {
var restaurantInfo = Restaurants()
var body: some View {
NavigationView {
NavigationLink(
destination: DetailView(restaurantInfo: restaurantInfo.restaurantList[Int.random(in: 0...restaurantInfo.restaurantList.count-1)]),
label: {
Text("Randomize")
.font(.title3)
.fontWeight(.bold)
.padding()
.background(Color.red)
.foregroundColor(.white)
.clipShape(Capsule())
})
}
}
}
目前,这段代码从列表中随机选择一个餐厅,而不是每次点击它都从列表中随机选择一个新的餐厅。
NavigationLink
目的地在视图的第一次呈现时计算。所以,你随机计算只会被调用一次。一个解决方案是使用NavigationLink
惰性加载视图。有一个StackOverflow的答案,我从:(https://stackoverflow.com/a/61234030/560942)
struct ContentView : View {
var elements = [1,2,3,4,5,6,7]
var body: some View {
NavigationView {
NavigationLink(destination:
NavigationLazyView(DetailView(input: elements.randomElement()!))
) {
Text("Go to random")
}
}
}
}
struct NavigationLazyView<Content: View>: View {
let build: () -> Content
init(_ build: @autoclosure @escaping () -> Content) {
self.build = build
}
var body: Content {
build()
}
}
struct DetailView : View {
var input : Int
var body: some View {
Text("(input)")
}
}
现在,内容是惰性计算的,所以每次都是随机计算。