首页 > 解决方案 > 有没有办法在 UIAlertAction 中获取文本字段值?

问题描述

我正在尝试在 Swift 中重构 UIAlert,我想确定是否有办法实现代码来实现我现在想要做的事情。

在我的应用程序中,我需要显示几个 UIAlertControllers,并且为了使文件变小,我正在制作一个自定义函数来显示 AlertController 并根据用户操作采取触发方法(我的意思是......当取消按下时,关闭弹出窗口等) .

我正在研究的是有一个 TextField,我想要实现的是当用户点击“确定”操作按钮时,获取 TextField 值的值。

在我的 UIVC+Alert.swift 文件中,我创建了一个扩展并添加了函数“showAlertWithTextField”,如下所示。

import UIKit

extension UIViewController {
    
    func showAlertWithTextField(title: String?, message: String?, actions: [UIAlertAction], style: UIAlertController.Style, completion: (() -> Void)?) {
        let alert = UIAlertController(title: title, message: message, preferredStyle: style)
        alert.addTextField { (textField) in
            print("textField \(textField.text)")
        }
        actions.forEach { alert.addAction($0)}
        present(alert, animated: true, completion: completion)
    }
}

那么,这个。函数是从其他 swift 文件 ViewController.swift 调用的。

func showAlert() {
    let editAction = UIAlertAction(title: "Edit", style: .destructive) { _ in

        // want to get the value of textFields in here...
        if let title = <How to access the textfield value ??> {
                print("title: \(title)")
        }
     }
     self.showAlertWithTextField(title: "test", message: nil, actions: [editAction], style: .alert, completion: nil)

}

通常,我不制作扩展文件,而是将所有内容都写在同一个文件中,因此我可以使用类似alert.textFields![0].text. 但是在这种情况下,当我在 showAlertWithTextField 函数中使用 alert.addTextField 时,用户没有输入任何内容并得到空字符串(这是有道理的)。但是当用户点击“编辑”按钮(触发editAction按钮)时,有没有办法访问警报的文本字段?

标签: iosswiftuitextfieldalertuialertview

解决方案


一种快速的方法是为文本字段添加一个临时变量和一个处理程序以将警报的文本字段分配给变量

func showAlert() {
    weak var textField : UITextField?

    let editAction = UIAlertAction(title: "Edit", style: .destructive) { _ in
        print("Edit Pressed", textField?.text ?? "n/a")
    }
    let handler : (UITextField) -> Void = { textField = $0 }
    self.showAlertWithTextField(title: "test", message: nil, actions: [editAction], style: .alert, handler: handler, completion: nil)

}

在添加文本字段后立即在扩展调用处理程序

extension UIViewController {
    
    func showAlertWithTextField(title: String?, message: String?,
                                actions: [UIAlertAction],
                                style: UIAlertController.Style,
                                handler: ((UITextField) -> Void)? = nil,
                                completion: (() -> Void)?) {
        let alert = UIAlertController(title: title, message: message, preferredStyle: style)
        alert.addTextField { handler?($0) }
        actions.forEach { alert.addAction($0)}
        present(alert, animated: true, completion: nil)
    }
}

推荐阅读