3

I would like to show an alert that contains an UIPickerView inside. Is it possible ? Any idea to do it ?

Thank you very much!

UPDATE

Finally I used this fantastic library to make cool custom alerts:

https://github.com/vikmeup/SCLAlertView-Swift

TibiaZ
  • 730
  • 1
  • 8
  • 21

1 Answers1

4

Try this:

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
    })
Amal T S
  • 3,327
  • 2
  • 24
  • 57
  • When the function is executed I get this error: "Could not cast value of type 'TwitterCampaigns.ViewController' (0x1088ac638) to 'UIPickerViewDataSource'". Any idea ? – TibiaZ Jul 31 '17 at 12:59
  • Did you added the datasource method to your viewController? – Amal T S Jul 31 '17 at 13:01
  • I've done it and the UIPickerView is showing but the data gets out of the alert box. – TibiaZ Jul 31 '17 at 13:10
  • Set the height of UIAlertView. Refer https://stackoverflow.com/a/28425340/7456236 – Amal T S Jul 31 '17 at 13:19