22

Is it possible to add image in an UIAlertView, like showing an image from the plist file?

Anbu.Karthik
  • 82,064
  • 23
  • 174
  • 143
summer
  • 269
  • 1
  • 4
  • 11

9 Answers9

42

You can do it like:

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];

This will add a image in the right corner of your alertview you can change the frame image to move around.

Hope this helps.

Niall Kiddle
  • 1,477
  • 1
  • 16
  • 35
Madhup Singh Yadav
  • 8,110
  • 7
  • 51
  • 84
  • works perfectly..thanks! but if i shift the image to the centre it will be blocked by the message..how can i do it in such a way that the image is in the centre then below the image would be the message? – summer Feb 24 '10 at 04:50
  • The only thing regarding this you can do is add another label for the message and append \n\n\n... in the end of your title This is the only way I know which does not uses the non-documented features. – Madhup Singh Yadav Feb 24 '10 at 07:20
  • 1
    Will apple approve the application if you add an images to UIAlertView ? – Illep Jan 23 '12 at 01:41
  • 8
    For anyone coming here from google, this no longer works in iOS7. You can however look into [this](https://github.com/wimagguc/ios-custom-alertview) which is a replica of UIAlertView with image support. – Jamie Taylor Oct 16 '13 at 09:09
  • 1
    http://stackoverflow.com/a/22861794/17239 is a short and effective extension for iOS 7. – Roger C S Wernersson Jun 23 '14 at 18:55
10

in iOS 7 or higher, use this code

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];
Quang Minh
  • 101
  • 1
  • 2
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];
Anbu.Karthik
  • 82,064
  • 23
  • 174
  • 143
5

You'll need to subclass UIAlertView and rearrange its subviews a bit. There are several tutorials for this kind of stuff:

Rob Napier
  • 286,113
  • 34
  • 456
  • 610
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];
picciano
  • 22,341
  • 9
  • 69
  • 82
0

Note for IOS 7 and above

if (floor(NSFoundationVersionNumber) > NSFoundationVersionNumber_iOS_6_1) {
    [alert setValue:imageView forKey:@"accessoryView"];
}else{
    [alert addSubview:imageView];
}
Ryan Heitner
  • 13,119
  • 6
  • 77
  • 119
0

Swift version:

    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()
  • How to adjust the size of the alert view or accessory view? If I use the above code, the alert is displayed for full size – AAA Dec 28 '15 at 10:20
  • by default, they don't provide any way to custom it. If you want to much more custom you should create a custom alert controller. (it is a sub class of uiviewcontroller) – Nguyễn Ngọc Bạn Dec 28 '15 at 10:55
0

I did some modification for the solution provided by Madhup.

The solution from Madhup work fine for short message, however, when the message is too long, message will be covered by image.

Hence, I added the following steps in method of UIAlertViewDelegate - (void)willPresentAlertView:(UIAlertView *)alertView

  1. Add 8 "\n" as prefix of message, to push the message down, reserving space for image (my image was restricted in 100x150)

  2. Detect the subviews of AlertView, to find out if UITextView exists.

    UITextView will exist only when the message is too long.

  3. If the UITextView does not exist, everything will be fine, image shown good, message shown good.

  4. If the UITextView exists, remove the 8 prefix "\n" from UITextView.text, and then call UITextView.setFrame to resize and change the position of the UITextview.

The above action works fine.

I send an NSDictionary as the message to be shown, the dictionary contains 2 key-value pairs, "msg"=>real message string. "url"=>as the image from web site.

With the NSURLConnection sendSynchronousRequest method, the code will retrieve image data from internet on the way.

- (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];
            }
        }        
    }
}
Dennies Chang
  • 564
  • 5
  • 15
-1

Using pure layout 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];
user1232690
  • 481
  • 5
  • 16