Skip to content

maximbilan/UIAlertController-Customization

Repository files navigation

Customization of UIAlertController

Recently I’m faced with an unusual task using UIAlertController. First, add an image to some of items. And the second, add UISwitch control.

alt tag

I know it doesn’t matсh Apple design flow, but maybe someone will come in handy for resolving different tasks.

The first, how to add an image. UIAlertController or UIAlertAction has not public methods for this, but you can do this via setValue for key ‘image’. For example:

alertAction.setValue(UIImage(named: "image1.png"), forKey: "image")

But you will get no good result.

alt tag

Please create a version of this image with the specified rendering mode. In our case with AlwaysOriginal.

alertAction.setValue(UIImage(named: "image1.png")?.imageWithRenderingMode(UIImageRenderingMode.AlwaysOriginal), forKey: "image")

And see what we will get:

alt tag

The second thing, how to add a switch control? 

Let’s create a new view controller and a user interface for this.

alt tag

import UIKit

class SwitchAlertActionViewController: UIViewController {
  @IBOutlet weak var valueSwitch: UISwitch!
  var isSwitchOn = false
 
  override func viewDidLoad() {
    super.viewDidLoad()

    valueSwitch.on = isSwitchOn
  }
}

And the last point, we need to apply this controller to UIAlertAction. The same way using a key contentViewController.

let switchAlert = SwitchAlertActionViewController()
switchAlert.isSwitchOn = true
alertAction.setValue(switchAlert, forKey: "contentViewController")

alt tag