24

I am new in swift and I am trying to make UIAlertContoller with PickerView but I have problems with the Buttones, Here a photo

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)
} 
Jeroen
  • 1,168
  • 1
  • 12
  • 24
Sahar Vanunu
  • 345
  • 2
  • 5
  • 19

1 Answers1

84

Instead of adding pickerView as subview try to set contentViewController of UIAlertController like this.

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

Nirav D
  • 71,513
  • 12
  • 161
  • 183
  • i try to feedback but i dont have reputation – Sahar Vanunu Oct 22 '16 at 10:58
  • @SaharVanunu Welcome mate :) – Nirav D Oct 22 '16 at 11:00
  • This may be broken in the iOS11 sdk. – Patrick Mar 16 '18 at 04:38
  • 3
    Note that according to documentation you should not modify UIAlertController view hierarchy: https://developer.apple.com/documentation/uikit/uialertcontroller "The view hierarchy for this class is private and must not be modified." and this solution uses private api (that is setValue(vc, forKey: "contentViewController")) – Leszek Szary Jul 20 '21 at 18:54