Defining a UIPickerView inside a UIAlertView

I am trying to put UIPickerViewin UIAlertView, but I cannot change it correctly. Here is what I get:

enter image description here

Here is 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)
+4
source share
1 answer

Trick:

  • use multiple lines for a message to provide space for your new presentation
  • adjust the size of the new view when presenting the warning.

    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

+6
source

Source: https://habr.com/ru/post/1665108/


All Articles