'Getting the result of input from one view to another SwiftUI [closed]
I have this view:
struct CreateBoardView: View {
@State public var BoardName: String = ""
var body: some View {
ZStack {
VStack {
TextField("Board name", text: self.$BoardName)
}
}
}
And then, when info is entered in this text field, I want to send it to another view. How to do this?
Solution 1:[1]
This is a possibility:
struct CreateBoardView: View {
@State var boardName = ""
var body: some View {
VStack(spacing: 20) {
TextField("Board name", text: $boardName)
AnotherView(boardName: $boardName)
}.padding()
}
}
struct AnotherView: View {
@Binding var boardName: String
var body: some View {
HStack {
Text("Transfered text: \(boardName)")
Spacer()
}
}
}
struct CreateBoardView_Previews: PreviewProvider {
static var previews: some View {
CreateBoardView()
}
}
Also you can use a ViewModel and transfer text through it:
struct CreateBoardView: View {
@StateObject var vm = ViewModel() //Here we create ViewModel, notice vm = ViewModel()
var body: some View {
VStack(spacing: 20) {
TextField("Board name", text: $vm.boardName)
AnotherView(vm: vm)
}.padding()
}
}
class ViewModel: ObservableObject {
@Published var boardName = ""
}
struct AnotherView: View {
@ObservedObject var vm: ViewModel //Here we observe ViewModel, notice vm: ViewModel, also you can observe the ViewModel in more views you'll create, not only this one.
var body: some View {
HStack {
Text("Transfered text: \(vm.boardName)")
Spacer()
}
}
}
struct CreateBoardView_Previews: PreviewProvider {
static var previews: some View {
CreateBoardView()
}
}
//BTW, use caps for first letters in struct and class names, and for variables the first letter should always be small.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |