How to pass a fieldtext value from view another view swiftui - swift

I put the fieldtext in view called fieldtextmydesine and also put the button in view named login and I called fieldtextmydesin view and login view in contentview how do I print the field text value when I press the login button

So you want to use NavigationView and NavigationLink instead of a button.
struct ContentView: View {
#State var name: String = "Tim"
var body: some View {
NavigationView {
VStack {
TextField("Enter your name", text: $name)
Text("Hello, \(name)!")
NavigationLink(destination: SecondView(name: self.$name)){
Text("LogIn")
}
}
}
}
//Second ContenView
struct SecondView: View {
#Binding var name: String
var body: some View {
Text("Hello \(text)")
}
}
From what I understand from your question, you are trying to pass a value entered into a Text-Field from one View to another. If this is what your asking then this is the best solution.

This snippet can help you:
You can bind property to textfield like this
struct ContentView: View {
#State private var name: String = "Tim"
var body: some View {
VStack {
TextField("Enter your name", text: $name)
Text("Hello, \(name)!")
}
}
}
You can add button and print name on button tap line you need. You can pass name property to another text on tap. Or hide text view and show on tap and another ways

You can display print name either on the console or can display name in an alert. In the below snippet, to fetch name entered in text field on button click requires state variable instead of normal variable. It is created with #State keyword. State parameter manages the state in the View. So whenever there is change in state all the components that are associated with the state will be rendered again.
import SwiftUI
struct LoginUI: View {
#State var textName: String = ""
#State var showAlert = false
var body: some View {
VStack(alignment: .center, spacing: 2.0) {
TextField("Enter your name", text: $textName).padding(10)
Button(action: {
print("Entered name is \(self.textName)")
self.showAlert = true
}, label: {Text("Login")}).padding().background(Color.gray)
}
.padding(5.0)
.alert(isPresented: $showAlert) {
Alert(title: Text("Entered name is"), message: Text("\(self.textName)"))
}
}
}
struct LoginUI_Previews: PreviewProvider {
static var previews: some View {
LoginUI()
}
}

Related

SwiftUI .searchable new view

I am creating an app and I am using .searchable for my home view, but once it is clicked, I want it to bring up a new view where results of what is being searched is shown, and once the cancel button is clicked goes back to the home view.
I currently have .searchable(text: $searchText) and it is showing the search bar, and I have tried .overlay{SearchView()} but it is just putting it over the home view. Is there a way to do this.
You need to use the #Environment variable isSearching to determine which view to display, e.g.
struct ContentView: View {
#State private var searchText = ""
var body: some View {
NavigationView {
SearchingView(searchText: $searchText)
.searchable(text: $searchText, placement: .navigationBarDrawer(displayMode: .always), prompt: "Search")
.navigationTitle("Title")
}
}
}
struct SearchingView: View {
#Environment(\.isSearching) private var isSearching
#Binding var searchText: String
var body: some View {
if isSearching {
List("This is displayed when searching".components(separatedBy: " "), id: \.self) { word in
Text(word )
}
.listStyle(.plain)
} else {
Text("Here is the normal view")
}
}
}

How to create a function for the button to print the data typed in texfields in the console

struct ContentView: View {
#State private var name : String = ""
var body: some View {
NavigationView{
Form{
Button(action: {
print(Textfield)
}) {
Text("Salvar")
}
I need to print the result typed at Textfield.
You are confusing the view, TextField, which allows you to input text with the variable which stores the result of the input. You can't print the view into which you type, but you can print the value of the variable. Therefore:
struct ContentView: View {
// name holds the value
#State private var name : String = ""
var body: some View {
NavigationView{
Form{
// TextField lets you change the value
TextField("Name", text: $name)
Button(action: {
// prints the value to the console
print(name)
}) {
Text("Salvar")
}
}
}
}
}

SwiftUI keyboard-shortcut without modifier doesn't work in popover

In a View with a textfield I have a popover, activated by a button.
In that popover I want to listen to a keyboardShortcut without modifiers.
These keypresses arrive in the textfild of the parent view instead of the popover.
What can I do, to react on these in the popover?
struct ContentView: View {
#State var showPopOver = false
#State var text = ""
var body: some View {
VStack{
TextField("enter text here", text: $text)
Button("show popover"){ showPopOver = true }
.popover(isPresented: $showPopOver) {PopOverView(text: $text)} }
.keyboardShortcut("p")
.padding()
}
}
struct PopOverView: View {
#Environment(\.dismiss) var dismiss
#Binding var text: String
var body: some View {
VStack{
Text("my Popover")
Button("set Tom"){
text = "Tom"
dismiss()
}
.keyboardShortcut("t",modifiers: [])
//.keyboardShortcut("t") // like this it works
Button("set Frank"){
text = "Frank"
dismiss()
}
.keyboardShortcut("f",modifiers: [])
}
.padding()
}
}
KeyboardShortcuts with a modifier in the popover do work (commented out).

SwiftUI View textfield not binding to ViewModel properties

I am creating a user signup with a NavigationView. The user enters an email, then they must enter
a username, password, etc.
After the user enters text the navigation link becomes active so they can continue to the next view and enter more details.
However the data entered is not binding with the properties in the ViewModel, I am using one ViewModel for all the data entry views in the NavigationView stack.
Why are the properties not binding/saving in the SignupViewModel? I know they aren't because I tried printing them after tapping the NavigationLink...
Thank you!
// ViewModel for all views in the stack
class SignupViewModel: ObservableObject {
var email = ""
var username = ""
var password = ""
var reconfirmPassword = ""
func sendEmailCode() { } // sends secret code to email for verification
}
// 1st view in NavigationView stack
struct SignupEmailView: View {
#ObservedObject var signupViewModel = SignupViewModel()
var emailContinueDisabled: Bool {
signupNavigationViewModel.email.isEmpty
}
var body: some View {
NavigationView {
VStack {
HStack {
Image(systemName: EMAIL_ICON)
TextField("enter your e-mail", text: $signupNavigationViewModel.email )
.autocapitalization(.none)
}
.modifier(DetailsTextFieldModifier())
NavigationLink("continue", destination: ConfirmCodeView())
.disabled(emailContinueDisabled)
Spacer()
}
}.navigationBarBackButtonHidden(true)
.navigationBarHidden(true)
}
}
// 2nd view in NavigationView stack
struct ConfirmCodeView: View {
#ObservedObject var signupNavigationViewModel = SignupNavigationViewModel()
var codeContinueDisabled: Bool {
signupNavigationViewModel.emailCode.isEmpty
}
var body: some View {
VStack {
TextField("Enter code sent to your email", text: $signupNavigationViewModel.emailCode)
NavigationLink("confirm", destination: SignupUsername())
.disabled(codeContinueDisabled)
Spacer()
}.navigationBarBackButtonHidden(true)
}
}
You are using computed property which they are not supported until today in SwiftUI Views, try to use State, Binding or ObservableObject directly.
struct SignupEmailView: View {
#StateObject var signupViewModel = SignupViewModel()
var body: some View {
NavigationView {
VStack {
HStack {
Image(systemName: EMAIL_ICON)
TextField("enter your e-mail", text: $signupViewModel.email)
.autocapitalization(.none)
}
.modifier(DetailsTextFieldModifier())
NavigationLink("continue", destination: ConfirmCodeView())
.disabled(signupViewModel.email.isEmpty) // <<: Here
Spacer()
}
}
.navigationBarBackButtonHidden(true)
.navigationBarHidden(true)
}
}
struct ConfirmCodeView: View {
#StateObject var signupNavigationViewModel = SignupNavigationViewModel()
var body: some View {
VStack {
TextField("Enter code sent to your email", text: $signupNavigationViewModel.emailCode)
NavigationLink("confirm", destination: SignupUsername())
.disabled(signupNavigationViewModel.emailCode.isEmpty) // <<: Here
Spacer()
}
.navigationBarBackButtonHidden(true)
}
}

Swiftui: how to watch variable binded to text field always

I am using Swift-UI for creating my app.
There is an AccountView is listing user's attributes and you can update it.
Once you click an Update button on the user's variable row of the list, navigate to EditVariableView, where you can change the variable with Text Field.
Of course, the text field has a validation of the inputted text, and you can commit the change by the Submit button on the right-up corner of EditVariableView.
For validation of the input, I use onCommit, detecting the change of the input, but here is a problem.
When you touch the text field, the keyboard comes out, and also you can input the text. But onCommit emits an event only when you close the keyboard.
If you input the text and click the Submit button without closing the keyboard, certainly onCommit does not emit an event for the validation. So, of course, the validation won't be done.
I want you to tell me, how to detect the input change on every text change.
You can disable Submit button if TextField is in editing state
import SwiftUI
struct ContentView: View {
#State var txt: String = ""
#State var editingFlag = false
var body: some View {
VStack {
TextField("text", text: $txt, onEditingChanged: { (editing) in
self.editingFlag = editing
}) {
print("commit")
}.padding().border(Color.red)
Button(action: {
print("submit")
}) {
Text("SUBMIT")
}.disabled(editingFlag)
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
SwiftUI 2.0
With the Xcode 12 and from iOS 14, macOS 11, or any other OS contains SwiftUI 2.0, there is a new modifier called 'onChange' that detects any change of the given state and can be performed on any view. So with some minor refactoring:
struct ContentView: View {
#State var txt: String = ""
#State var editingFlag = false
var body: some View {
VStack {
TextField("text", text: $txt)
.onChange(of: txt) {
print("Changed to :\($0)")
}
}
.padding()
.border(Color.red)
Button("SUBMIT") {
print("submit")
}
.disabled(editingFlag)
}
}
from: hacking with with Swift. Paul Hudson
struct ContentView : View {
#State private var name = ""
var body: some View {
TextField("Enter your name:", text: $name)
.textFieldStyle(RoundedBorderTextFieldStyle())
.onChange(of: name) { newValue in
print("Name changed to \(name)!")
}
}
}