Sizing a UIPickerView inside a UIAlertView

5.2k Views Asked by At

I'm trying to put a UIPickerView in a UIAlertView however I can't seem to size it correctly. Here's what I'm getting:

enter image description here

Here's my code:

    let alertView = UIAlertController(title: "Select item from list", message: "", preferredStyle: UIAlertControllerStyle.alert)

    let pickerView = UIPickerView(frame: CGRect(x: 0, y: 0, width: 250, height: 60))
    pickerView.dataSource = self
    pickerView.delegate = self

    alertView.view.addSubview(pickerView)

    let action = UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil)

    alertView.addAction(action)
    parent.present(alertView, animated: true, completion: nil)
1

There are 1 best solutions below

2
On BEST ANSWER

The trick is:

  • use multiple lines for message to give space for your new view
  • adjust the size of the new view when the alert view is presented

    let alertView = UIAlertController(
        title: "Select item from list",
        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
    
    // comment this line to use white color
    pickerView.backgroundColor = UIColor.lightGray.withAlphaComponent(0.2)
    
    alertView.view.addSubview(pickerView)
    
    let action = UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil)
    
    alertView.addAction(action)
    present(alertView, animated: true, completion: { _ in
        pickerView.frame.size.width = alertView.view.frame.size.width
    })
    

enter image description here