xcode 带有pickerView按钮动作的swift UIAlertController

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/40190629/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 09:28:54  来源:igfitidea点击:

swift UIAlertController with pickerView button action stay up

swiftxcodeswift3uipickerviewuialertcontroller

提问by Sahar Vanunu

I am new in swift and I am trying to make UIAlertContollerwith PickerViewbut I have problems with the Buttones, Here a photo

我是 swift 的新手,我正在尝试制作UIAlertContollerPickerView但我对 Buttones 有问题,这是一张照片

enter image description here

在此处输入图片说明

I am trying to change the constraint of the buttons to stay up. I read a lot of answers here but I did not find any solution

我正在尝试更改按钮的约束以保持状态。我在这里阅读了很多答案,但没有找到任何解决方案

Here is my code:

这是我的代码:

func distance(){
    let editRadiusAlert = UIAlertController(title: "Choose distance", message: "", preferredStyle: UIAlertControllerStyle.alert)
    let pickeViewFrame: CGRect = CGRect(x: 0, y: 0, width: 250, height: 300)
    let pickerViewRadius: UIPickerView = UIPickerView(frame: pickeViewFrame)
    pickerViewRadius.delegate = self
    pickerViewRadius.dataSource = self
    editRadiusAlert.view.addSubview(pickerViewRadius)
    editRadiusAlert.addAction(UIAlertAction(title: "Done", style: UIAlertActionStyle.default,handler:nil))
    editRadiusAlert.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.cancel, handler: nil))
    editRadiusAlert.view.addConstraint(NSLayoutConstraint(item: editRadiusAlert.view, attribute: NSLayoutAttribute.height, relatedBy: NSLayoutRelation.equal, toItem: nil, attribute: NSLayoutAttribute.notAnAttribute, multiplier: 1, constant: self.view.frame.height * 0.5))
    self.present(editRadiusAlert, animated: true, completion: nil)
} 

回答by Nirav D

Instead of adding pickerViewas subview try to set contentViewControllerof UIAlertControllerlike this.

取而代之的将pickerView作为子视图尝试设置contentViewControllerUIAlertController这个样子。

let vc = UIViewController()
vc.preferredContentSize = CGSize(width: 250,height: 300)
let pickerView = UIPickerView(frame: CGRect(x: 0, y: 0, width: 250, height: 300))
pickerView.delegate = self
pickerView.dataSource = self
vc.view.addSubview(pickerView)
let editRadiusAlert = UIAlertController(title: "Choose distance", message: "", preferredStyle: UIAlertControllerStyle.alert)
editRadiusAlert.setValue(vc, forKey: "contentViewController")
editRadiusAlert.addAction(UIAlertAction(title: "Done", style: .default, handler: nil))
editRadiusAlert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
self.present(editRadiusAlert, animated: true)

It's looks like below.

它看起来像下面。

enter image description here

在此处输入图片说明