Created
September 11, 2016 17:17
-
-
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)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// 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
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)
}
@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
how to use this extension
Please hlp