如何在 UIAlertController 中添加 UIImageView?

How to add UIImageView in UIAlertController?

我希望 UIAlertControllerActionSheet 中显示带有 UIImageView 的警报。但是当我 运行 应用程序正在终止时。

这是我的代码:

UIAlertController *alert = [UIAlertController
                                  alertControllerWithTitle:@"Title"
                                  message:@"Welcome"
                                  preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *okButton = [UIAlertAction
                            actionWithTitle:OK
                            style:UIAlertActionStyleDefault
                            handler:^(UIAlertAction *action)
                            {
                            }];
[alert addAction:okButton];
UIImageView *imgv = [[UIImageView alloc]initWithFrame:CGRectMake(20,20,50,50)];
imgv.image = [UIImage imageNamed:@"kaga.jpg"];
[alert setValue:imgv forKey:@"image"];
[self presentViewController:alert animated:YES completion:nil];

根据 Apple Doc,无法将图像添加到 UIAlertController

如果需要,您可以创建自己的自定义视图,例如:

https://github.com/wimagguc/ios-custom-alertview

如果要拍照出现在button 然后像这样尝试:

UIAlertController * alert = [UIAlertController alertControllerWithTitle:@"Title"
                              message:@"Welcome"
                              preferredStyle:UIAlertControllerStyleActionSheet];

UIAlertAction* okButton = [UIAlertAction actionWithTitle:@"OK"
                            style:UIAlertActionStyleCancel
                            handler:^(UIAlertAction * action) {
                              //Do some thing here
                            }];

[okButton setValue:[[UIImage imageNamed:@"kaga.jpg"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forKey:@"image"];

[alert addAction:okButton];
[self presentViewController:alert animated:YES completion:nil];

您可以通过对 UIAlertController 进行子类化并将 \n 添加到标题字符串来为 UIImageView 创建 space,从而在标题标签上方添加图像。您必须根据字体大小计算布局。对于 UIAlertAction 中的图像,请像这样使用 KVCself.setValue(image, forKey: "image")。我建议使用检查 responds(to:) 的扩展。

Here is sample implementation.

extension UIAlertAction {

    /// Image to display left of the action title
    var actionImage: UIImage? {
        get {
            if self.responds(to: Selector(Constants.imageKey)) {
                return self.value(forKey: Constants.imageKey) as? UIImage
            }
            return nil
        }
        set {
            if self.responds(to: Selector(Constants.imageKey)) {
                self.setValue(newValue, forKey: Constants.imageKey)
            }
        }
    }

    private struct Constants {
        static var imageKey = "image"
    }
}

改变这个:

UIImageView *imgv=[[UIImageView alloc]initWithFrame:CGRectMake(20,20,50,50)];
    imgv.image=[UIImage imageNamed:@"kaga.jpg"];
    [alert setValue:imgv  forKey:@"image"];

对此:

UIImage *img= [UIImage imageNamed:@"kaga.jpg"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    [alert setValue:img  forKey:@"image"];