【问题标题】:refreshing RandomElement() in SwiftUI在 SwiftUI 中刷新 RandomElement()
【发布时间】:2021-07-25 10:36:29
【问题描述】:

我有一个想要使用按钮刷新的颜色列表。这就是我现在所拥有的。

var body: some View {
        
        let happy = ["red","blue","purple","green"]
        let randomHappy = happy.randomElement()!
        
        ZStack {
            
            Rectangle()
                .foregroundColor(/*@START_MENU_TOKEN@*/.blue/*@END_MENU_TOKEN@*/)
                .ignoresSafeArea()
            
            VStack{
            
            Text(randomHappy)
            
            Button(action: /*@START_MENU_TOKEN@*/{}/*@END_MENU_TOKEN@*/, label: {
                Text("Button")
                    .foregroundColor(.black)
            })
            }
                
        }
        
    }
}


我考虑过刷新整个页面,但我认为仅仅刷新随机元素的结果可能太过分了。有人知道如何解决这个问题吗?

【问题讨论】:

    标签: xcode swiftui xcode12


    【解决方案1】:

    您可以使用@State 存储数组中的随机元素。

    struct ContentView: View {
        static let happy = ["red","blue","purple","green"]
    
        @State var randomHappy = Self.happy.randomElement()!
        
        var body: some View {
            
            ZStack {
                
                Rectangle()
                    .foregroundColor(.blue)
                    .ignoresSafeArea()
                
                VStack{
                    
                    Text(randomHappy)
                    
                    Button(action: {
                        randomHappy = Self.happy.randomElement()!
                    }) {
                        Text("Button")
                            .foregroundColor(.black)
                    }
                }
                
            }
        }
    }
    

    在几乎所有正常情况下,我不建议使用! 强制解包,但在这种情况下,您可以保证您总是能取回一个元素,所以这似乎是合理的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-22
      • 2021-07-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-07-22
      • 2019-10-22
      • 2019-11-29
      相关资源
      最近更新 更多