1
votes

Comment pouvons-nous ajouter `Button` et` TextField` en utilisant `SwiftUI`

J'apprends SwiftUI (nouveau framework fourni par Apple avec iOS 13 et Xcode 11: SwiftUI par Apple ).

Je souhaite ajouter Button et TextField dans ListView avec une action. Je veux qu'un champ de texte dans cet utilisateur puisse ajouter n'importe quel nombre de 1 à 10, puis appuyer sur le bouton ENVOYER . Quelqu'un a une idée de comment ajouter un bouton et comment pouvons-nous gérer l ' événement tactile de Button avec SwiftUI ?

Toute aide serait appréciée.


0 commentaires

5 Réponses :


7
votes

Voici une vue simple contenant un champ de texte et un bouton dans une pile horizontale.

Pour gérer l'interaction de l'utilisateur avec dans votre Button , écrasez simplement l ' action code > fermeture.

import SwiftUI

struct ButtonAndTextFieldView : View {

    @State var text: String = ""

    var body: some View {
        HStack {
            TextField($text,
                      placeholder: Text("type something here..."))
            Button(action: {
                // Closure will be called once user taps your button
                print(self.$text)
            }) {
                Text("SEND")
            }
        }
    }
}

#if DEBUG
struct ButtonWithTextFieldView_Previews : PreviewProvider {
    static var previews: some View {
        ButtonWithTextFieldView()
    }
}
#endif


1 commentaires

J'obtiens "Erreur fatale: accès à l'état en dehors de View.body" sur la ligne TextField avec ce code.



1
votes

Vous pouvez ajouter un bouton comme celui-ci

@State var bindingString: Binding<String> = .constant("")

TextField(bindingString,
          placeholder: Text("Hello"),
          onEditingChanged: { editing in
              print(editing)
          }).padding(.all, 40)

Et un champ de texte.

Button(action: {}) {
    Text("Increment Total")
}


0 commentaires

0
votes

ListView avec champ de texte et bouton. Vous aurez besoin d'un identifiant pour chaque ligne au cas où vous voudriez avoir plusieurs lignes dans la liste.

struct ListView: View {

@State var text: String = ""

var body: some View {
    List {
        ForEach (1..<2) {_ in
            Section {
                HStack(alignment: .center) {
                    TextField(self.$text, placeholder: Text("type something here...") ).background(Color.red)
                    Button(action: {
                        print(self.$text.value)
                    } ) {
                        Text("Send")
                    }
                }
            }
        }
    }
}

}


0 commentaires

3
votes

Pour la conception de la page de connexion, vous pouvez utiliser cette section de code. Avec le champ de texte de bordure textFieldStyle et le type de contenu définis.

struct ButtonAndTextFieldView : View {

    @State var email: String = ""
    @State var password: String = ""

    var body: some View {
        VStack {
            TextField($email,
            placeholder: Text("email"))
            .textFieldStyle(.roundedBorder)
            .textContentType(.emailAddress)

           TextField($password,
                placeholder: Text("password"))
                .textFieldStyle(.roundedBorder)
                .textContentType(.password)

            Button(action: {
               //Get Email and Password
                print(self.$email)
                print(self.$password)
            }) {
                Text("Send")
            }
        }
    }


1 commentaires

Le fait est que vous devez toujours gérer le clavier vous-même s'il couvre l'interface utilisateur. :( J'espérais une solution dans SwiftUI mais ne semble pas avoir de guichet automatique.



0
votes

Vous pouvez écrire un TextField personnalisé qui vous renverra l'événement dans la fermeture une fois que l'utilisateur aura appuyé sur le bouton. Ce champ de texte personnalisé contiendrait un HStack avec un champ de texte et un bouton. Comme ça.

  struct ListView: View {

      @State var text: String = ""

      var body: some View {
           List {
                ForEach (1..<2) {_ in
                    Section {
                            CustomTextField(
                                           text: self.$text,
                                           action: {
                                              print("number is .....\(self.text)")
                                           },
                                           buttonTitle: "Submit",
                                           placeholder: "enter your number")
                            }
                   }
            }
     }
 }

Et vous pouvez utiliser ce TextField personnalisé comme ceci. J'ai utilisé un exemple des réponses énumérées ci-dessus pour le rendre plus clair.

struct CustomTextField : View {

      @Binding var text: String

      var editingChanged: (Bool)->() = { _ in }
      var commit: ()->() = { }
      var action : () -> Void

      var buttonTitle : String
      var placeholder: String

      var isSecuredField = false

      var body : some View {
           HStack {
               if isSecuredField {
                   SecureField(placeholder, text: $text, onCommit: commit)
               } else {
                   TextField(placeholder, text: $text, onEditingChanged: editingChanged, onCommit: commit)
               }
           Button(action: action) {
            Text(buttonTitle)
        }
      }
   }
}


0 commentaires