Skip to content

Instantly share code, notes, and snippets.

@AppleBetas
Created September 11, 2016 17:17
Show Gist options
  • Save AppleBetas/6d707e244680e2f071c09e1c9dcf478f to your computer and use it in GitHub Desktop.
Save AppleBetas/6d707e244680e2f071c09e1c9dcf478f to your computer and use it in GitHub Desktop.
UIAlertAction+Image.swift - An easier way to add images to UIAlertActions (alerts and action sheets)
//
// UIAlertAction+Image.swift
//
// Created by AppleBetas on 2016-09-11.
// Copyright © 2016 AppleBetas. All rights reserved.
//
import UIKit
extension UIAlertAction {
convenience init(title: String?, style: UIAlertActionStyle, image: UIImage, handler: ((UIAlertAction) -> Void)? = nil) {
self.init(title: title, style: style, handler: handler)
self.actionImage = image
}
convenience init?(title: String?, style: UIAlertActionStyle, imageNamed imageName: String, handler: ((UIAlertAction) -> Void)? = nil) {
if let image = UIImage(named: imageName) {
self.init(title: title, style: style, image: image, handler: handler)
} else {
return nil
}
}
var actionImage: UIImage {
get {
return self.value(forKey: "image") as? UIImage ?? UIImage()
}
set(image) {
self.setValue(image, forKey: "image")
}
}
}
@AkAyush
Copy link

AkAyush commented Aug 20, 2018

how to use this extension

Please hlp

@SashaTsebrii
Copy link

SashaTsebrii commented Sep 10, 2018

@AkAyush
I'm using this and another small extension for UIImage:

extension UIImage {
    func imageWithSize(scaledToSize newSize: CGSize) -> UIImage {
        UIGraphicsBeginImageContextWithOptions(newSize, false, 0.0)
        self.draw(in: CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height))
        let newImage: UIImage = UIGraphicsGetImageFromCurrentImageContext()!
        UIGraphicsEndImageContext()
        return newImage
    }
}

How to use:

func showAlert() {
    let alertController = UIAlertController()
    let action = UIAlertAction(title: "Title", style: .default) { (action: UIAlertAction!) in
        // ...
        }
        
    let image = UIImage(named: "Photo")
    if let image = image?.imageWithSize(scaledToSize: CGSize(width: 30, height: 30)) {
        action.setValue(image, forKey: "image")
    }
    
    alertController.addAction(action)
    self.present(alertController, animated: true, completion: nil)
}

@ErAshu
Copy link

ErAshu commented Jan 5, 2021

@aydenp How to left align action title

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment