如何将图像添加到 UIAlertView? [复制]

Posted

技术标签:

【中文标题】如何将图像添加到 UIAlertView? [复制]【英文标题】:How to add image into UIAlertView? [duplicate] 【发布时间】:2016-06-20 05:11:48 【问题描述】:

我想在 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 无法提供图像。请帮帮我

【问题讨论】:

【参考方案1】:
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];

【讨论】:

感谢您的帮助。现在通过使用此代码。图像出现在警报视图中,但出现在底部并从左到右拉伸。 更改图像视图框架【参考方案2】:

首先将您的图片添加到图片资源中并命名为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];

【讨论】:

【参考方案3】:

适用于 iOS 7.0 +

用途:

[successAlert setValue:imageView forKey:@"accessoryView"];

【讨论】:

以上是关于如何将图像添加到 UIAlertView? [复制]的主要内容,如果未能解决你的问题,请参考以下文章

如何将图像背景添加到不透明的文本中? [复制]

如何在 iOS7 中将 UIDatePicker 添加到 UIALertView

如何在 iOS 8 中使用 UIAlertView? [复制]

将 UITextfield 添加到 UIAlertView

将 UIImage 添加到 UIAlertView 未按预期工作

将 UIActivityIndi​​catorView 添加到 UIAlertView