I want to make button, which pressed will show us random textfield (from 3 textfields: username, username2 or username3). Currently I have something like this, but don't know how to make it possible.
struct Test: View {
/// @State private var names : ??? - I don't know what should be there
@State private var username: String = ""
@State var username2: String = ""
@State var username3: String = ""
var body: some View {
NavigationView {
VStack {
TextField("Your name", text: $username)
TextField("Your name2", text: $username2)
TextField("Your name3", text: $username3)
Button(action: randomName) {
Text("draw")
}
}
Text("names.text") /// it doesn't work
.foregroundColor(.black)
.font(.largeTitle)
}
}
}
private func randomName() {
let names = ["\(username)", "\(username2)", "\(username3)"]
}
}
I have tried to add everything into first @State private var names, but nothing work properly. Maybe I am just trying in wrong way? Or it shouldn't be done by 'let names'? I don't know and have no idea.
CodePudding user response:
first of all you just need to add randomName as State.
struct Example: View {
@State private var username: String = ""
@State var username2: String = ""
@State var username3: String = ""
@State var selectedName: String = "Initial Value"
var body: some View {
NavigationView {
VStack {
TextField("Your name", text: $username)
TextField("Your name2", text: $username2)
TextField("Your name3", text: $username3)
Button(action: randomName) {
Text("draw")
}
Text(selectedName)
.foregroundColor(.black)
.font(.largeTitle)
}
}
}
private func randomName() {
let names = ["\(username)", "\(username2)", "\(username3)"]
selectedName = names[Int.random(in: 0..<names.count)]
}
}