如何将图像添加到 UIAlertView?

How to add image into UIAlertView?

我想在 UIAlertView 的左上角添加图像。

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

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

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


[successAlert addSubview:imageView];

[successAlert show];

我正在使用这段代码,但图像没有出现在 UIAlertView 中。请帮助我

对于iOS 7.0 +

使用:

[successAlert setValue:imageView forKey:@"accessoryView"];
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];

首先将您的图片添加到图片资产中,并将名称命名为 imgCloud 然后将您的代码更新为:

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

UIImageView *imageViewCloud = [[UIImageView alloc] initWithFrame:CGRectMake(5, 5, 40, 40)];
UIImage *bkgImg = [UIImage imageNamed:@"imgCloud"];
[imageViewCloud setImage:bkgImg];
[successAlert imageViewCloud forKey:@"accessoryView"];
[successAlert show];