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)
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:
Swift 4:
var imageView = UIImageView(frame: CGRect(x: 220, y: 10, width: 40, height: 40))
imageView.image = <#yourImage#>
alert.view.addSubview(imageView)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With