Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Action Sheet with Image for each option on iOS

Tags:

ios

swift

iphone

Is there any way to add an images to action sheet on iOS ? Same as apple do on there app store or apple musics app. My basic search on apple docs indicated that I don't subclass or add sub view in Action Sheet.

"UIActionSheet is not designed to be subclassed, nor should you add views to its hierarchy." -- Apple Docs

enter image description here

like image 764
AAV Avatar asked Dec 03 '22 20:12

AAV


1 Answers

Swift 4: If the image is larger and it doesn't fit well, use this code and UIImage Extension to resize the image:

func showAlert() {
    let alertController = UIAlertController()
    let action = UIAlertAction(title: "Title", style: .default) { (action: UIAlertAction!) in
    }
    if let icon = icon?.imageWithSize(scaledToSize: CGSize(width: 32, height: 32)) {
        action.setValue(icon, forKey: "image")
    }

    alertController.addAction(action)
    self.present(alertController, animated: true, completion: nil)
}

And use this extension:

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
    }

}
like image 151
Diego Carrera Avatar answered Dec 17 '22 11:12

Diego Carrera