Search code examples
iosswiftalignmentuialertcontroller

Center align image action in UIAlertController


I have a UIAlertController:

let alert = UIAlertController(title: "Add your photo", message: "", preferredStyle: .alert)

var image = UIImage(named: "avatar.png")

image = image?.withAlignmentRectInsets(UIEdgeInsetsMake(0, view.frame.width/2 - (image?.size.width)!/2, 0, 0))

let imageAction = UIAlertAction(title: "", style: .default, handler: nil)

imageAction.setValue(image?.withRenderingMode(.alwaysOriginal), forKey: "image")

alert.addAction(imageAction)

By default, the icon is being left aligned and I tried to center align it by using UIEdgeInset (line 3 above). Considering the top left corner being the origin (0,0), I tried to position the image at the center along the horizontal axis with the left inset value as in the code but the image is obtained as below. So I know this is not correct. I can manage to get it in the center by trial and error. But I would like to come up with a proper way to center align it. What would be the right way to achieve this? Thank you.

enter image description here


Solution

  • You shouldn't use forKey: "image", because is a private api.

    If you want to add an image inside an alert controller, you might try with NSLayoutConstraint, doing so:

    let alert = UIAlertController(title: "Add your photo", message: "\n\n\n", preferredStyle: .alert)
    alert.addAction(UIAlertAction(title: "Upload", style: .default, handler: nil))
    alert.addAction(UIAlertAction(title: "Add later", style: .default, handler: nil))
    let image = UIImageView(image: UIImage(named: "avatar"))
    alert.view.addSubview(image)
    image.translatesAutoresizingMaskIntoConstraints = false
    alert.view.addConstraint(NSLayoutConstraint(item: image, attribute: .centerX, relatedBy: .equal, toItem: alert.view, attribute: .centerX, multiplier: 1, constant: 0))
    alert.view.addConstraint(NSLayoutConstraint(item: image, attribute: .centerY, relatedBy: .equal, toItem: alert.view, attribute: .centerY, multiplier: 1, constant: 0))
    alert.view.addConstraint(NSLayoutConstraint(item: image, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: 64.0))
    alert.view.addConstraint(NSLayoutConstraint(item: image, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: 64.0))
    self.present(alert, animated: true, completion: nil)
    

    result is:

    enter image description here