Adding an image to a UIAlertController

user5349223 picture user5349223 · Sep 26, 2015 · Viewed 20.1k times · Source

This is my alert that works perfectly. I want to add an image to the alert that shows up along side the text when the alert is presented and I'm in an SKScene in SpriteKit if it makes a difference.

var alertController = UIAlertController(title: "How to Skate", message: "Tap the screen to perform a trick and jump over the obsticles (You can grind on rails) The game will end when you hit a highlighted red, orange or yellow obstacle. That's it! + Image", preferredStyle: UIAlertControllerStyle.Alert)     
alertController.addAction(UIAlertAction(title: "Cool!", style: UIAlertActionStyle.Cancel, handler: nil))
self.view?.window?.rootViewController?.presentViewController(alertController, animated: true, completion: nil)

Answer

Abhinav picture Abhinav · Sep 26, 2015

You can add a UIImageView as a subview to your UIAlertController.

var imageView = UIImageView(frame: CGRectMake(220, 10, 40, 40))
imageView.image = yourImage
alert.view.addSubview(imageView)

This is how you do in UIAlertController:

let alertMessage = UIAlertController(title: "My Title", message: "My Message", preferredStyle: .Alert)

let image = UIImage(named: "myImage")
var action = UIAlertAction(title: "OK", style: .Default, handler: nil)
action.setValue(image, forKey: "image")
alertMessage .addAction(action)

self.presentViewController(alertMessage, animated: true, completion: nil)