25

I have an alert view that pops up when the user press the add button. How do i add an image to the alert view?

I added some code that i took reference from stack overflow. My save button is replaced with the image and the image appear to be in blue colour...

Code for Alert View

var alert = UIAlertController(title: "Spring Element \(springNumber)",
            message: "Add spring properties",
            preferredStyle: .Alert)

        let saveAction = UIAlertAction(title: "Save",
            style: .Default) { (action: UIAlertAction!) -> Void in

                let textField1 = alert.textFields![0] as UITextField
                self.txtField1.append(textField1.text)
                self.tableView.reloadData()

                let textField2 = alert.textFields![1] as UITextField
                self.txtField2.append(textField2.text)
                self.tableView.reloadData()

                println(self.txtField1)
                println(self.txtField2)
        }

        let cancelAction = UIAlertAction(title: "Cancel",
            style: .Default) { (action: UIAlertAction!) -> Void in
        }

        //adding textfield1
        alert.addTextFieldWithConfigurationHandler {
            (textField1: UITextField!) -> Void in
            textField1.placeholder = "Force"
        }

        //adding textfield2
        alert.addTextFieldWithConfigurationHandler {
            (textField2: UITextField!) -> Void in
            textField2.placeholder = "Stiffness"
        }

        alert.addAction(saveAction)
        alert.addAction(cancelAction)

        presentViewController(alert,
            animated: true,
            completion: nil)

Code for Image View

   let image = UIImage(named: "springAtWall")
    saveAction.setValue(image, forKey: "image")
    alert.addAction(saveAction)
Eric Aya
  • 69,473
  • 35
  • 181
  • 253
Cherry_thia
  • 696
  • 1
  • 10
  • 24

6 Answers6

34

Yes, you can add a UIImageView as a subview to your alert view.

var imageView = UIImageView(frame: CGRect(x: 220, y: 10, width: 40, height: 40))
imageView.image = yourImage

alert.view.addSubview(imageView)
shim
  • 9,289
  • 12
  • 69
  • 108
Christian
  • 22,585
  • 9
  • 80
  • 106
  • I replaced yourImage with the name of my image. It gives an error: use of unresolved identifier 'springAtWall'. There is an error with the last line; 'UIAlerController' does not have a member named 'addSubView'. – Cherry_thia Feb 05 '15 at 14:31
  • I've edited my answer. You have to call alert.view.addSubview. – Christian Feb 05 '15 at 14:50
  • It works. This subview appears at right side of the title of the alert view and the image displayed is too small. Is there a way to place it below the message? And I want to increase the dimension as well. What does the numbers, (220, 10, 40, 40) represent? – Cherry_thia Feb 05 '15 at 14:57
  • 1
    Thanks for the solution. However this is bit too small. Is there any suggestion to make the image bigger and appear below the message but above the textfield? – Cherry_thia Feb 05 '15 at 15:05
  • Yes. Make the ImageView bigger. – Christian Feb 05 '15 at 15:24
  • How would you make the image a background image, behind the text? – μολὼν.λαβέ Apr 26 '15 at 22:35
  • 1
    This method is explicitly forbidden by Apple. Also, the CGRectMake() doesn't work as you need to pass a negative y value to position the image toward the center. – slider Jul 14 '15 at 22:59
  • @chicobermuda "This method is explicitly forbidden" where mentioned ? – Umair Afzal Nov 30 '16 at 11:03
  • Hello bro @Christian, could you please take a look to my problem http://stackoverflow.com/questions/42715152/how-add-image-into-uialertbox-in-swift-3/42718242#42718242 ? – May Phyu Mar 11 '17 at 04:15
  • On the surface, it seems fine, but it's not a good approach. This breaks when users change the text size in Accessibility Settings. The alert view text runs into the image and can become covered. – user4806509 Aug 05 '17 at 22:14
  • @Christian Can't add big image. My image has size 200x150 and it's overlap the alertviewcontroller – AnLT Apr 13 '18 at 04:09
  • 1
    @chicobermuda I know it's a long time on now, but for the record, the documentation forbidding the adjustment of an alert controller can be found here: https://developer.apple.com/documentation/uikit/uialertcontroller. Note the 'Important' box-off which says `The UIAlertController class is intended to be used as-is and does not support subclassing. The view hierarchy for this class is private and must not be modified.` – Ash Jun 01 '18 at 07:10
26

Here is the solution for Swift 4:

let showAlert = UIAlertController(title: "Demo Alert", message: nil, preferredStyle: .alert)
let imageView = UIImageView(frame: CGRect(x: 10, y: 50, width: 250, height: 230))
imageView.image = image // Your image here...
showAlert.view.addSubview(imageView)
let height = NSLayoutConstraint(item: showAlert.view, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 320)
let width = NSLayoutConstraint(item: showAlert.view, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 250)
showAlert.view.addConstraint(height)
showAlert.view.addConstraint(width)
showAlert.addAction(UIAlertAction(title: "OK", style: .default, handler: { action in
    // your actions here...    
}))
self.present(showAlert, animated: true, completion: nil)

Output will be somehow like below for all iPhones:

Alert with Image

Hardik Trivedi
  • 613
  • 7
  • 10
  • 1
    That is my mistake, it is not 'showQRCodeAlert', it is 'showAlert'. We need to configure any view in alert by alert's root view. So i have edited that answer, you can check that out. – Hardik Trivedi Feb 22 '19 at 08:33
  • 1
    Great solution, just what I needed. – Jonas May 01 '19 at 16:32
7

Swift 4:

var imageView = UIImageView(frame: CGRect(x: 220, y: 10, width: 40, height: 40))
imageView.image = <#yourImage#>
alert.view.addSubview(imageView)
Eric Aya
  • 69,473
  • 35
  • 181
  • 253
Gustavo Vollbrecht
  • 3,188
  • 2
  • 19
  • 37
5

We can add image as one option in alert view controller like this.

   let imageView = UIImageView(frame: CGRect(origin: CGPoint(x: 0,y :0), size: CGSize(width: 196, height: 196)))
    imageView.image = image

    UIGraphicsBeginImageContextWithOptions(imageView.bounds.size, imageView.isOpaque, 0.0)
    defer { UIGraphicsEndImageContext() }
    let context = UIGraphicsGetCurrentContext()
    imageView.layer.render(in: context!)
    let finalImage = UIGraphicsGetImageFromCurrentImageContext()

    let alertMessage = UIAlertController(title: "Your Title", message: "", preferredStyle: .alert)
    let action = UIAlertAction(title: "", style: .default, handler: nil)
    action.setValue(finalImage?.withRenderingMode(UIImageRenderingMode.alwaysOriginal), forKey: "image")
    alertMessage .addAction(action)
    let action1 = UIAlertAction(title: "OK", style: .default, handler: nil)
    alertMessage .addAction(action1)

    self.present(alertMessage, animated: true, completion: nil)
0

It wasn't immediately clear to me what @Kakumanu's ImageContext stuff was for, but that's to resize the UIImage. Perhaps a slightly more Swifty way of doing it would be through a UIImage extension ```

extension UIImage {
/// Resize a UIImage
func imageWith(newSize: CGSize) -> UIImage {
    let renderer = UIGraphicsImageRenderer(size: newSize)
    let image = renderer.image { _ in
        self.draw(in: CGRect.init(origin: CGPoint.zero, size: newSize))
    }
    return image.withRenderingMode(self.renderingMode)
 }
}
Fabio
  • 5,432
  • 4
  • 22
  • 24
spfursich
  • 5,045
  • 3
  • 21
  • 24
0
func launchAlertTool(image: UIImage, topViewController: UIViewController) {
        let alert = UIAlertController(title: "Add Comments",
                                      message: nil,
                                      preferredStyle: .alert)
        
        let subview = (alert.view.subviews.first?.subviews.first?.subviews.first!)! as UIView
        subview.backgroundColor = UIColor(red: (145/255.0), green: (200/255.0), blue: (0/255.0), alpha: 1.0)
        let imageView = UIImageView(frame: CGRect(x: 0, y: 100, width: topViewController.view.bounds.width, height: topViewController.view.bounds.width - 150))
        imageView.image = image
        imageView.contentMode = .scaleAspectFit
        alert.view.addSubview(imageView)
        alert.view.tintColor = .black
        
        let height = NSLayoutConstraint(item: alert.view as Any, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: topViewController.view.bounds.width)
        let width = NSLayoutConstraint(item: alert.view as Any, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: topViewController.view.bounds.width)
        alert.view.addConstraint(height)
        alert.view.addConstraint(width)
        
        alert.addTextField { (textField) in
            // optionally configure the text field
            textField.keyboardType = .alphabet
            textField.textAlignment = .center
            textField.tintColor = .systemPink
        }
        
        let okAction = UIAlertAction(title: "Share", style: .default) { [unowned alert] (action) in
            if let textField = alert.textFields?.first {
                let comment = textField.text ?? "Check this image"
                let shareAll = [comment, screenShot] as [Any]
                let activityViewController = UIActivityViewController(activityItems: shareAll, applicationActivities: nil)
                activityViewController.popoverPresentationController?.sourceView = topViewController.view
                topViewController.navigationController?.present(activityViewController, animated: true, completion: {
                })
            }
        }
        alert.addAction(okAction)
        if let topVC = UIApplication.getTopViewController() {
            topVC.present(alert, animated: true, completion: {
            })
        }
    }
PradeepKN
  • 617
  • 7
  • 10