![](/img/trans.png)
[英]How to check validation of TextField on Button Tap (not by using NavigationLink) in SwiftUI?
[英]How can we add `Button` and `TextField` by using `SwiftUI`
我正在学习SwiftUI
(Apple 提供的带有 iOS 13 和 Xcode 11 的新框架: Apple SwiftUI )。
我想通过操作在ListView
添加Button
和TextField
。 我希望该用户中的一个文本字段可以添加 1 到 10 之间的任何一个数字,然后点击SEND
按钮。 任何人都知道如何在其中添加按钮以及我们如何使用SwiftUI
处理Button
touch event
?
任何帮助将不胜感激。
这是一个简单的视图,它在水平堆栈中包含一个文本字段和一个按钮。
要处理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")
}
}
}
}
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.