Home>

Xcode 12.2
iOS 14.2

I set the image (1024x1024 PNG) in the UIAlertAction with the setValue method because it is possible to display the image in ActionSheet, but the image was not displayed but only the blue square was displayed. What is the cause.

func selectAppIcon () {
        let alert: UIAlertController = UIAlertController (title: "You can change the app icon.", message: "Choose your favorite app icon.", preferredStyle: UIAlertController.Style.actionSheet)
                var defaultAction: UIAlertAction = UIAlertAction (title: "normal version", style: .default, handler: {
                    (action: UIAlertAction!)->Void in
                    UIApplication.shared.setAlternateIconName ("a.png")
                })
                var defaultAction1: UIAlertAction = UIAlertAction (title: "pattern version", style: .default, handler: {
                    (action: UIAlertAction!)->Void in
                    UIApplication.shared.setAlternateIconName (".png")
                })
                let cancelAction: UIAlertAction = UIAlertAction (title: "Cancel", style: .cancel, handler: nil)
        let image = UIImage (named: "b.png")? .Resize (size: CGSize (width: 50, height: 50))

        defaultAction.setValue (image, forKey: "image")
        defaultAction1.setValue (UIImage (named: "b.png")? .resize (size: CGSize (width: 50, height: 50)), forKey: "image")
                alert.addAction (defaultAction)
                alert.addAction (defaultAction1)
                alert.addAction (cancelAction)
                present (alert, animated: true, completion: nil)
            }
extension UIImage {
    func resize (size _size: CGSize)->UIImage? {
        let widthRatio = _size.width/size.width
        let heightRatio = _size.height/size.height
        let ratio = widthRatio<heightRatio? widthRatio: heightRatio
        let resizedSize = CGSize (width: size.width * ratio, height: size.height * ratio)
        UIGraphicsBeginImageContextWithOptions (resizedSize, false, 0.0) // Change
        draw (in: CGRect (origin: .zero, size: resizedSize))
        let resizedImage = UIGraphicsGetImageFromCurrentImageContext ()
        UIGraphicsEndImageContext ()
        return resizedImage
    }
}

Actual display when executing the above code

  • Answer # 1

    I solved it myself.
    I'm not sure why.

    Don't resize

    Do not dynamically resize (self-made logic) after loading UIImage

    let image = UIImage (named: "b.png")? .Resize (size: CGSize (width: 50, height: 50))


    Therefore, it is necessary to prepare a small image in advance according to the place to display.

    Call withRenderingMode
    let image = UIImage (named: "Le_1024.png_50.png") ?. withRenderingMode (UIImage.RenderingMode.alwaysOriginal)


    And it seems that it is necessary to call withRenderingMode.