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 overfl
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:
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)
}
}
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)
Swift 4:
var imageView = UIImageView(frame: CGRect(x: 220, y: 10, width: 40, height: 40))
imageView.image = <#yourImage#>
alert.view.addSubview(imageView)
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)