能否在UIAlertView中显示图片?

22

是否可以在UIAlertView中添加图像,例如从plist文件中显示图像?

9个回答

42

你可以这样做:

UIAlertView *successAlert = [[UIAlertView alloc] initWithTitle:title message:message delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];

    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(220, 10, 40, 40)];

    NSString *path = [[NSString alloc] initWithString:[[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"smile.png"]];
    UIImage *bkgImg = [[UIImage alloc] initWithContentsOfFile:path];
    [imageView setImage:bkgImg];

    [successAlert addSubview:imageView];

    [successAlert show];

这将在你的警告框右上角添加一张图片,你可以更改框架图像来移动它。

希望这有所帮助。


工作得非常完美,谢谢!但是如果我将图像移动到中心,它将被消息阻挡。我该如何做到这样,使图像位于中心,然后在图像下方是消息? - summer
关于这件事,你唯一可以做的是为消息添加另一个标签,并在标题末尾添加\n\n\n...。这是我所知道的唯一不使用非文档特性的方法。 - Madhup Singh Yadav
1
如果您在UIAlertView中添加图像,苹果是否会批准该应用程序? - Illep
8
对于从Google来到这里的任何人,需要说明的是,此方法在iOS7已经不再适用。不过,您可以查看这个链接:https://github.com/wimagguc/ios-custom-alertview,它是一个支持图片的UIAlertView复制品。 - Jamie Taylor
1
https://dev59.com/-WMl5IYBdhLWcg3wDjSg#22861794 是一个短小而有效的iOS 7扩展。 - Roger C S Wernersson

10

在 iOS 7 或更高版本中,请使用以下代码:

UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 200, 282)];
UIImage *wonImage = [UIImage imageNamed:@"iberrys.png"];
imageView.contentMode=UIViewContentModeCenter;
[imageView setImage:wonImage];
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Arirang List"
                                                     message:@"phiên bản: 1.0\n website: www.iberrys.com\n email: quangminh@berrys.com\nmobile: 0918 956 456"
                                                    delegate:self
                                           cancelButtonTitle:@"Đồng ý"
                                           otherButtonTitles: nil];
//check if os version is 7 or above
if (floor(NSFoundationVersionNumber) > NSFoundationVersionNumber_iOS_6_1) {
    [alertView setValue:imageView forKey:@"accessoryView"];
}else{
    [alertView addSubview:imageView];
}
 [alertView show];

@QuangMing,你的代码调用了两次UIAlertview。我不明白为什么? - Muju

5
UIAlertView *Alert = [[UIAlertView alloc] initWithTitle:@"your Title" message:@"Your   Message" delegate:nil cancelButtonTitle:@"Your Title" otherButtonTitles:nil];

UIImageView *image = [[UIImageView alloc] initWithFrame:CGRectMake(0,0, 40, 40)];

NSString *loc = [[NSString alloc] initWithString:[[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"Your Image Name"]];
UIImage *img = [[UIImage alloc] initWithContentsOfFile:loc];
[image setImage:img];

if (floor(NSFoundationVersionNumber) > NSFoundationVersionNumber_iOS_6_1) {
    [Alert setValue:image forKey:@"accessoryView"];
}else{
    [Alert addSubview:image];
}

[Alert show];

[alertView setValue:imageView forKey:@"accessoryView"]; 翻译为中文:[alertView setValue:imageView forKey:@"accessoryView"]; - user3182143
[action setValue:accessoryImage forKey:@"image"]; [action setValue:accessoryImage forKey:“image”]; - user3182143

5

1
但我认为重新排列子视图可能会导致应用程序被拒绝。 - Madhup Singh Yadav

2
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 200, 282)];
UIImage *wonImage = [UIImage imageNamed:@"iberrys.png"];
imageView.contentMode = UIViewContentModeCenter;
[imageView setImage:wonImage];
UIAlertView *alertView = [[UIAlertView alloc]  initWithTitle:@"Arirang List"
                                                     message:@"phiên bản: 1.0\n website: www.iberrys.com\n email: quangminh@berrys.com\nmobile: 0918 956 456"
                                                    delegate:self
                                           cancelButtonTitle:@"Đồng ý"
                                           otherButtonTitles:nil];
//check if os version is 7 or above
if (floor(NSFoundationVersionNumber) > NSFoundationVersionNumber_iOS_6_1) {
    [alertView setValue:imageView forKey:@"accessoryView"];
} else {
    [alertView addSubview:imageView];
}
[alertView show];

0

注意:适用于iOS 7及以上版本

if (floor(NSFoundationVersionNumber) > NSFoundationVersionNumber_iOS_6_1) {
    [alert setValue:imageView forKey:@"accessoryView"];
}else{
    [alert addSubview:imageView];
}

0

Swift版本:

    let alertView = UIAlertView(title: "Alert", message: "Alert + Image", delegate: nil, cancelButtonTitle: "OK")
    let imvImage = UIImageView(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
    imvImage.contentMode = UIViewContentMode.Center
    imvImage.image = UIImage(named: "image_name")
    alertView.setValue(imvImage, forKey: "accessoryView")
    alertView.show()

如何调整警告视图或附加视图的大小?如果我使用上面的代码,警告将以全尺寸显示。 - AAA
默认情况下,它们不提供任何自定义的方式。如果您想要更多的自定义,您应该创建一个自定义警报控制器(它是UIViewController的子类)。 - Nguyễn Ngọc Bạn

0

我对Madhup提供的解决方案进行了一些修改。

Madhup的解决方案适用于短消息,但是当消息过长时,消息将被图像覆盖。

因此,我在UIAlertViewDelegate方法中添加了以下步骤- (void)willPresentAlertView:(UIAlertView *)alertView

  1. 在消息前添加8个"\n",将消息向下推,为图像保留空间(我的图像受到100x150的限制)

  2. 检测AlertView的子视图,查找UITextView是否存在。

    只有当消息过长时,UITextView才会存在。

  3. 如果UITextView不存在,则一切都很好,图像显示良好,消息显示良好。

  4. 如果UITextView存在,则从UITextView.text中删除8个前缀"\n",然后调用UITextView.setFrame来调整UITextview的大小和位置。

上述操作效果良好。

我发送一个NSDictionary作为要显示的消息,该字典包含2个键值对,“msg”=>真实消息字符串。“url”=>作为来自网站的图像。

使用NSURLConnection的sendSynchronousRequest方法,代码将从互联网中获取图像数据。
- (void)showAlertView:(NSDictionary *)msgDic {
    NSLog(@"msgDic = %@", msgDic);
    NSMutableString *msg = [[NSMutableString alloc] initWithString:@"\n\n\n\n\n\n\n\n"];
    if ([msgDic objectForKey:@"msg"]) {
        [msg appendFormat:@"%@", [msgDic objectForKey:@"msg"]];
    }
    else {
        [msg setString:[msgDic objectForKey:@"msg"]];
    }

    NSLog(@"msg = %@", msg);
    UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"Alert Title"
                                                message:msg
                                               delegate:self
                                    cancelButtonTitle:@"Close" otherButtonTitles:nil];

     if ([msgDic objectForKey:@"url"]) {
         NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:[msgDic objectForKey:@"url"]]];
         [request setCachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData];

         NSData *imgData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
         if (imgData) {
             UIImage *shownImage = [UIImage imageWithData:imgData];
             UIImageView *imgView = [[UIImageView alloc] initWithImage:shownImage];
             [imgView setFrame:CGRectMake(floor(284-100)/2.0, 47, 100, 150)];

             [alert addSubview:imgView];
             [imgView release];
         }
     }

    alert.delegate = self;
    [alert show];
    [alert release];
    [msgDic release];
}

- (void)willPresentAlertView:(UIAlertView *)alertView {
int viewCount = [alertView.subviews count];

    NSLog(@"subviews count = %i", viewCount);

    if (viewCount > 0) {
        BOOL bFoundTextView = NO;
        for (int count=0; count<=[alertView.subviews count] -1; count++) {
            BOOL bIsTextView = NO;
            UIView *subView = [alertView.subviews objectAtIndex:count];
            NSLog(@"view index %i classname = %@", count, [[subView class] description]);

            bIsTextView = [[[subView class] description] isEqualToString:@"UIAlertTextView"];
            bFoundTextView |= bIsTextView;

            if (bIsTextView) {
                UITextView *textView = (UITextView *)subView;
                NSMutableString *msg = [[NSMutableString alloc] initWithString:textView.text];
                [msg setString:[msg substringFromIndex:8]];
                textView.text = msg;

                CGRect frame = textView.frame;
                if (frame.origin.y != 205) {
                    frame.origin.y = 205;
                    frame.size.height -= 155;
                    [textView setFrame:frame];
                }

                [msg release];
            }
        }        
    }
}

-1
使用纯布局Pod:
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"Hello"
                                                                         message:nil
                                                                  preferredStyle:UIAlertControllerStyleAlert];
UIImage *image = // target image here;
CGSize size = image.size;
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(leftMargin, topMargin, size.width, size.height)];
imageView.image = image;
[alertController.view addSubview:imageView];
[imageView autoPinEdgeToSuperviewEdge:ALEdgeLeft withInset:leftMargin];
[imageView autoPinEdgeToSuperviewEdge:ALEdgeTop withInset:topMargin];
[imageView autoPinEdgeToSuperviewEdge:ALEdgeRight withInset:rightMargin];
[imageView autoPinEdgeToSuperviewEdge:ALEdgeBottom withInset:bottomMargin];
[imageView autoSetDimension:ALDimensionWidth toSize:size.width];
[imageView autoSetDimension:ALDimensionHeight toSize:size.height];
// add desired actions here
[self presentViewController:alertController animated:YES completion:nil];

UIImageView没有声明选择器“autoPinEdgeToSuperviewEdge:withInset:”,请检查您的代码。 - kemdo
我明确说过,它是使用纯布局oid制作的。 - user1232690

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接