Add image to alert view

筅森魡賤 提交于 2019-12-03 00:46:34
Christian Wörz

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)

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:

Gustavo Vollbrecht

Swift 4:

var imageView = UIImageView(frame: CGRect(x: 220, y: 10, width: 40, height: 40))
imageView.image = <#yourImage#>
alert.view.addSubview(imageView)

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)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!