首页 > 解决方案 > 使用 addTextField(目标 iOS12.4)时 UIAlertController 在 Swift 5 中冻结 - 从目标 C 转换

问题描述

我的 Swift 视图控制器是从我的主要目标 C 应用程序中调用的。调用函数“showAlert()”会显示,但会冻结模拟器。我没有收到任何错误,但没有一个按钮起作用,并且文本字段没有抬起键盘(占位符出现)。(我的实际代码有更多的 alertActions,如果我注释掉 TextField 代码就可以正常工作)。我什至从 StackOverflow 复制逐字代码以显示带有 TextField 的基本警报控制器,它与下面写的问题相同。


@objc class MyVC :UIViewController {

@objc func showAlert() {
        let alertController = UIAlertController(title: "Title", message: "", preferredStyle: .alert)
        alertController.addTextField { (textField : UITextField!) -> Void in
            textField.placeholder = "Enter name"
        }

        let saveAction = UIAlertAction(title: "Confirm", style: .default, handler: { alert -> Void in
            if let textField = alertController.textFields?[0] {
                if textField.text!.count > 0 {
                    print("Text :: \(textField.text ?? "")")
                }
            }
        })

        let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: {
            (action : UIAlertAction!) -> Void in })

        alertController.addAction(cancelAction)
        alertController.addAction(saveAction)

        alertController.preferredAction = saveAction

        self.present(alertController, animated: true, completion: nil)
    }
}

'present(...' 处的断点显示分配的警报控制器,但从这里介入以警报控制器的冻结显示结束。非常感谢任何调试建议。

标签: swiftmigrationuitextfielduialertcontroller

解决方案


推荐阅读