【发布时间】: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)
}
}
【问题讨论】: