我正在学习SwiftUI
(Apple 提供的带有 iOS 13 和 Xcode 11 的新框架:Apple 的 SwiftUI)。
我想添加Button
并TextField
采取ListView
行动。我希望该用户中的一个文本字段可以添加从 1 到 10 的任何一个数字,然后点击SEND
按钮。任何人都知道如何在其中添加按钮以及我们touch event
如何Button
处理SwiftUI
?
任何帮助将不胜感激。
这是一个简单的视图,其中包含一个文本字段和一个水平堆栈中的按钮。
要在你的 中处理用户交互Button
,只需覆盖action
闭包。
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
对于登录页面设计,您可以使用此代码部分。带有 textFieldStyle 边框文本字段和内容类型集。
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")
}
}
}
你可以像这样添加按钮
Button(action: {}) {
Text("Increment Total")
}
和文本字段。
@State var bindingString: Binding<String> = .constant("")
TextField(bindingString,
placeholder: Text("Hello"),
onEditingChanged: { editing in
print(editing)
}).padding(.all, 40)
您可以编写一个自定义 TextField ,一旦用户点击按钮,它将在关闭中返回事件。此自定义文本字段将包含一个带有文本字段和按钮的 HStack。像这样。
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)
}
}
}
}
你可以像这样使用这个自定义的 TextField。我使用了上面列出的答案中的一个例子来使其更清楚。
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")
}
}
}
}
}
带有文本字段和按钮的 ListView。如果您想在列表中有多行,您将需要每行的标识符。
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")
}
}
}
}
}
}
}