到目前为止,我能够处理警报中显示的文本字段,用户可以在其中输入一些文本,但无法使用该文本并将其显示在应用程序内。
这是警报的代码:
private func alert() {
let alert = UIAlertController(title: "Enter Name", message: "...or pseudo", preferredStyle: .alert)
alert.addTextField { (textField) in
textField.placeholder = "Enter something"
}
alert.addAction(UIAlertAction(title: "Done", style: .default) { _ in })
let textField = alert.textFields![0] as UITextField
alertInput = textField.text ?? "Name"
showAlert(alert: alert)
}
func showAlert(alert: UIAlertController) {
if let controller = topMostViewController() {
controller.present(alert, animated: true)
}
}
这就是我试图在体内实现它的方式:
Section {
VStack {
Button(action: {
withAnimation {
self.alert()
}
}) {
Text(alertInput)
}
}
}
alertInput
像这样在主体之前初始化:
@State private var alertInput = ""
您将需要从“完成”按钮的处理程序中获取文本字段的值。因此,您需要做的就是向下移动支架:
alert.addAction(UIAlertAction(title: "Done", style: .default) { _ in
let textField = alert.textFields![0] as UITextField
alertInput = textField.text ?? "Name"
})
当用户点击您已设置的UIAlertAction时,将调用此闭包中的代码。
请注意,如果将该字段保留为空,则值textField.text
will为""
and not nil
,因此,为了使用您提供的默认值,您可能还需要一些其他逻辑来检查空白字符串。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句