【问题标题】:How do I access a random value from the restaurantList each time I tap the randomize button每次点击随机化按钮时,如何从 restaurantList 访问随机值
【发布时间】:2021-10-13 18:32:27
【问题描述】:
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())
                })
            
        }

    }
}

目前,此代码从列表中随机选择一家餐厅,并且每次点击它时都不会从列表中选择一家新的随机餐厅。

【问题讨论】:

  • 数组有随机元素方法

标签: swift mvvm swiftui xcode12


【解决方案1】:

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)")
    }
}

现在内容是惰性计算的,所以每次都是随机计算。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-07-21
    • 2014-11-11
    • 2018-11-15
    • 2021-11-14
    • 1970-01-01
    • 1970-01-01
    • 2021-01-30
    相关资源
    最近更新 更多