在 UIAlertView 中设置 TextField 和 PickerView

Set TextField and PickerView In UIAlertView

我想创建一个带有文本字段和选择器视图的警报。 我希望首先在顶部显示选择器视图,然后在选择器视图下方显示文本字段。

这是我的代码

let alert = UIAlertController(title: "Create Meditation", message: "myMsg", preferredStyle: .alert)

alert.view.addSubview(pickerView)

alert.addTextField { (textField) in
textField.text = "Enter Message"

}


let action = UIAlertAction(title: "Send", style: .default) { (action) in
    let textField = alert.textFields

    print(textField)

            }
let action2 = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)

alert.addAction(action)
alert.addAction(action2)

let height:NSLayoutConstraint = NSLayoutConstraint(item: alert.view, attribute: NSLayoutAttribute.height, relatedBy: NSLayoutRelation.equal, toItem: nil, attribute: NSLayoutAttribute.notAnAttribute, multiplier: 1, constant: self.view.frame.height * 0.50)
    alert.view.addConstraint(height);

self.present(alert, animated: true, completion: nil)

您不能为此使用 UIAlertController,因为它没有添加文本字段以外的视图的选项。 因此,您必须编写自己的控件,以模仿 UIAlertController。 您可以编写视图控制器并以模态方式呈现它,或者创建一个视图并将其添加到控制器视图中。 另外,尝试在 github.com or cocoacontrols.com 上找到现成的组件并根据需要修改它可能是个好主意。

你应该创建一个 uiviewcontroller 并赋予它这种效果。

例如:在下图中,我创建了一个模态视图。它是一个带有灰色视图的 uiviewcontroller(在你的例子中,你应该在灰色视图中放置 uitextfield 和 uipickerview)。然后,我将故事板 segue 配置为模态呈现,并在 uiviewcontroller 中给出模态的效果:

self.view.backgroundColor = UIColor.black.withAlphaComponent(0.8)

试试这些Pods希望对你有帮助

https://github.com/nealyoung/NYAlertViewController

您可以使用以下代码:

 let alertView = UIAlertController(
            title: "Select",
            message: "\n\n\n\n\n\n\n\n\n",
            preferredStyle: .alert)

        let pickerView = UIPickerView(frame:
            CGRect(x: 0, y: 50, width: 260, height: 162))
        pickerView.dataSource = self
        pickerView.delegate = self
        pickerView.backgroundColor = UIColor.lightGray.withAlphaComponent(0.5)

        alertView.view.addSubview(pickerView)
        alertView.addTextField(configurationHandler: configurationTextField)
        alertView.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler:nil))
        alertView.addAction(UIAlertAction(title: "Ok", style: .default, handler:{ (UIAlertAction) in
            guard let text = self.textField?.text else {return}
            print(text)
        }))
        present(alertView, animated: true, completion: {
            pickerView.frame.size.width = alertView.view.frame.size.width
        })