Adding an image to a UIAlertController
If you're willing to use private APIs you could use the private attributedMessage
property to set an attributed string as message containing an image:
Source: https://github.com/JaviSoto/iOS10-Runtime-Headers/blob/master/Frameworks/UIKit.framework/UIAlertController.h
let actionSheet = UIAlertController(title: "title", message: nil, preferredStyle: .actionSheet)
let str = NSMutableAttributedString(string: "Message\n\n", attributes: [NSAttributedStringKey.font: UIFont.preferredFont(forTextStyle: .caption1), NSAttributedStringKey.foregroundColor: UIColor.gray])
let attachment = NSTextAttachment()
attachment.image = --> yourImage <--
str.append(NSAttributedString(attachment: attachment))
actionSheet.setValue(str, forKey: "_attributedMessage")
Again, this is a private API and therefore could change in any release without notice. To be used with caution!
let alertMessage = UIAlertController(title: "My Title", message: "", preferredStyle: .alert)
let action = UIAlertAction(title: "OK", style: .default, handler: nil)
action.setValue(UIImage(named: "task1.png")?.withRenderingMode(UIImageRenderingMode.alwaysOriginal), forKey: "image")
alertMessage .addAction(action)
self.present(alertMessage, animated: true, completion: nil)
Swift 3
You can do like this.
let imageView = UIImageView(frame: CGRectMake(220, 10, 40, 40))
// imageView.image = UIImage(named: "ic_no_data")
let alertMessage = UIAlertController(title: "My Title", message: "", preferredStyle: .Alert)
let image = UIImage(named: "Image")
let action = UIAlertAction(title: "OK", style: .Default, handler: nil)
action.setValue(image, forKey: "image")
alertMessage .addAction(action)
self.presentViewController(alertMessage, animated: true, completion: nil)
alertMessage.view.addSubview(imageView)
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)