Add image to alert view

Cherry_thia picture Cherry_thia · Feb 5, 2015 · Viewed 30.9k times · Source

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)

Answer

Christian picture Christian · Feb 5, 2015

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)