【问题标题】:SwiftUI : Display return value from a function to another viewSwiftUI:将函数的返回值显示到另一个视图
【发布时间】:2021-03-01 08:52:26
【问题描述】:

我必须在单击按钮时(在第一个视图中)生成一个随机字符串,然后在文本上显示该字符串(在第二个视图中),但现在我被困在用文本切换第二个视图。有人知道我如何绑定 func 的返回值并将其显示到第二个视图吗?

这是随机字符串的代码(来源:Generate random alphanumeric string in Swift

class randomString: ObservableObject{ 
  @Published var showDisplay: Bool = false
  @Published var s = ""

  func randomString(of length: Int) -> String { // return `String`
      let letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
      var s = ""
      for _ in 0 ..< length {
          s.append(letters.randomElement()!)
          print(s)
        
          goToDisplay()
      }
      return s
  }

  func goToDisplay(){
    
      self.showDisplay.toggle()
  }
}

在内容视图中,我通过单击按钮调用该函数;

struct ContentView: View {

   @StateObject var stringData = randomString()

   var body: some View {
    
       VStack{
           Text("Generate String")
               .font(.title)
               .fontWeight(.bold)
               .foregroundColor(.primary)
               .padding()
        
           Button(action: {
               //self.showDisplay.toggle()
               stringData.randomString(of: 5)
           }, label: {
               Text("Next Page")
                   .font(.title2)
                   .fontWeight(.light)
                   .foregroundColor(Color.white)
                   .scaledToFit()
                   .frame(maxWidth: .infinity)
                   .frame(height: 60, alignment: /*@START_MENU_TOKEN@*/.center/*@END_MENU_TOKEN@*/)
                   .background(Color.orange)
                   .cornerRadius(20)
                   .padding(.all,10)


           })
           .padding(.bottom, 40)
       }
       .fullScreenCover(isPresented: $stringData.goToDisplay, content: {
           DisplayView()
       })

    }
}

第二视图现在看起来像这样

struct DisplayView: View {

   @StateObject var stringData = randomString()
   @Environment(\.presentationMode) var presentationMode

   var body: some View {
       Text("Random String : \(stringData.s)")
           .font(.title)
           .fontWeight(.bold)
           .foregroundColor(.primary)
           .padding()
    
       Spacer()
    
       Button(action: {
           presentationMode.wrappedValue.dismiss()
       }, label: {
          Text("Close")
               .font(.title2)
               .fontWeight(.light)
               .foregroundColor(Color.white)
               .scaledToFit()
               .frame(width: UIScreen.main.bounds.width - 100)
               .frame(height: 50)
               .scaledToFit()
               .background(Color.orange)
               .cornerRadius(12)
               .padding(.bottom)
       })
       .padding(.horizontal)
   }
}

【问题讨论】:

    标签: swift swiftui


    【解决方案1】:

    只需改变你的流程。

    class RandomString: ObservableObject{
        
        @Published var s: String? = ""
        
        func randomString(of length: Int) { // return `String`
            let letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
            var s = ""
            for _ in 0 ..< length {
                s.append(letters.randomElement()!)
                print(s)
            }
            self.s = s
        }
    }
    
    struct ContentViewSecond: View {
        
        @StateObject var stringData = RandomString()
        @State var showDisplay = false
        var body: some View {
            
            VStack{
                Text("Generate String")
                    .font(.title)
                    .fontWeight(.bold)
                    .foregroundColor(.primary)
                    .padding()
                
                Button(action: {
                    self.showDisplay.toggle()
                    stringData.randomString(of: 5)
                }, label: {
                    Text("Next Page")
                        .font(.title2)
                        .fontWeight(.light)
                        .foregroundColor(Color.white)
                        .scaledToFit()
                        .frame(maxWidth: .infinity)
                        .frame(height: 60, alignment: /*@START_MENU_TOKEN@*/.center/*@END_MENU_TOKEN@*/)
                        .background(Color.orange)
                        .cornerRadius(20)
                        .padding(.all,10)
                    
                    
                })
                .padding(.bottom, 40)
            }
            .fullScreenCover(isPresented: $showDisplay) {
                DisplayView(stringData: stringData)
            }
        }
    }
    
    struct DisplayView: View {
        
        @ObservedObject var stringData: RandomString
        @Environment(\.presentationMode) var presentationMode
    
        var body: some View {
            Text("Random String : \(stringData.s ?? "")")
                .font(.title)
                .fontWeight(.bold)
                .foregroundColor(.primary)
                .padding()
         
            Spacer()
         
            Button(action: {
                presentationMode.wrappedValue.dismiss()
            }, label: {
               Text("Close")
                    .font(.title2)
                    .fontWeight(.light)
                    .foregroundColor(Color.white)
                    .scaledToFit()
                    .frame(width: UIScreen.main.bounds.width - 100)
                    .frame(height: 50)
                    .scaledToFit()
                    .background(Color.orange)
                    .cornerRadius(12)
                    .padding(.bottom)
            })
            .padding(.horizontal)
        }
     }
    

    【讨论】:

    • @StateObject 应该像一个单一的事实来源一样,不是在 DisplayView 中声明“@StateObject var stringData: RandomString”不正确吗?
    • @TusharSharma 你的观点是对的。但我只是重用OP代码。你可以编辑我的答案。
    猜你喜欢
    • 2019-05-10
    • 2022-11-22
    • 2010-09-15
    • 2021-08-14
    • 1970-01-01
    • 2021-12-16
    • 2021-04-01
    • 1970-01-01
    • 2020-10-04
    相关资源
    最近更新 更多