问题
I am learning SwiftUI
(New framework provided by Apple with iOS 13 and Xcode 11 : SwiftUI by Apple).
I want to add Button
and TextField
in ListView
with action. I want one textfield in that user can add any one number from 1 to 10 and then hit SEND
button. Anyone have any idea how to add button in it and also how can we handle touch event
of Button
with SwiftUI
?
Any help would be appreciate.
回答1:
Here is a simple view what contains a textfield and a button in a horizontal stack.
To handle the user interaction with in your Button
, just overwrite the action
closure.
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
回答2:
For the Login page design you can use this code section. With textFieldStyle border textfield and content type set.
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")
}
}
}
回答3:
You can add button like that
Button(action: {}) {
Text("Increment Total")
}
And text field.
@State var bindingString: Binding<String> = .constant("")
TextField(bindingString,
placeholder: Text("Hello"),
onEditingChanged: { editing in
print(editing)
}).padding(.all, 40)
回答4:
ListView with textfield and button. You will need an identifier for each row in case you want to have multiple rows in the List.
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")
}
}
}
}
}
}
}
来源:https://stackoverflow.com/questions/56449684/how-can-we-add-button-and-textfield-by-using-swiftui