将 UIImage 添加到 UIAlertView 未按预期工作
Posted
技术标签:
【中文标题】将 UIImage 添加到 UIAlertView 未按预期工作【英文标题】:Adding UIImage to UIAlertView is not working as expected 【发布时间】:2017-02-27 11:36:53 【问题描述】:我正在开发一个应用程序。我尝试使用以下代码将 UIIMage 添加到 UIAlertView,
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Instruction"
message:@"Please TAP on Screen to Continue."
delegate:self
cancelButtonTitle:@"OK"
otherButtonTitles:nil];
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(220, 50, 32, 32)];
UIImage *img = [UIImage imageNamed:@"pendingImg.png"];
[imageView setImage:img];
if (floor(NSFoundationVersionNumber) > NSFoundationVersionNumber_ios_6_1)
[alert setValue:imageView forKey:@"accessoryView"];
else
[alert addSubview:imageView];
[alert show];
我的图像尺寸为 32 × 32 像素。我收到如图所示的警报,
我应该为此图像添加约束吗?还是要做什么?
【问题讨论】:
您通常不应该乱用 UIAlertView 的视图继承。创建自己的警报样式视图会更安全,更不用说更好了。 尝试将 imageView 的内容模式更改为宽高比匹配。 检查它是否与 UIImageView 的 contentMode UIViewContentModeScaleAspectFit 一起工作 看到这个***.com/questions/2323557/… @Anbu.Karthik 我的问题是让图像看起来正常,上面的帖子是添加图像到 UIAlertView 【参考方案1】:您可以将imageView contentMode
设置为UIViewContentModeScaleAspectFit
,
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Instruction"
message:@"Please TAP on Screen to Continue."
delegate:self
cancelButtonTitle:@"OK"
otherButtonTitles:nil];
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(220, 50, 32, 32)];
UIImage *img = [UIImage imageNamed:@"pendingImg.png"];
imageView.contentMode = UIViewContentModeScaleAspectFit;
[imageView setImage:img];
if (floor(NSFoundationVersionNumber) > NSFoundationVersionNumber_iOS_6_1)
[alert setValue:imageView forKey:@"accessoryView"];
else
[alert addSubview:imageView];
[alert show];
可能Anbu.Karthik建议的链接评论对您也有帮助。
【讨论】:
如果您使用较大的尺寸,它会自动适合图像视图 imageView.contentMode = UIViewContentModeScaleAspectFit;是罪魁祸首:)【参考方案2】:试试这个
UIAlertView* alert = [UIAlertView alloc] initWithTitle: @"Instruction" message: @"Please TAP on Screen to Continue." delegate:nil cancelButtonTitle:@"no" otherButtonTitles:@"yes", nil];
UIImage* img = [UIImage imageNamed:@"pendingImg.png"];
UIImageView* imgview = [UIImageView alloc] initWithFrame:CGRectMake(0, 0, img.size.width, img.size.height)];
[img setImage:imgMyImage];
[alert setValue: imgview forKey:@"accessoryView"];
[alert show];
【讨论】:
它只是将图像添加到 UIAlertVIew,不知何故我用我的代码得到了它。【参考方案3】:UIAlertView* alert = [[UIAlertView alloc] initWithTitle: @"Instruction" message: @"Please TAP on Screen to Continue." delegate:nil cancelButtonTitle:@"no" otherButtonTitles:@"yes", nil];
UIImage* img = [UIImage imageNamed:@"add.png"];
UIImageView* imgview = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, img.size.width, img.size.height)];
[imgview setImage:img];
[alert setValue: imgview forKey:@"accessoryView"];
[alert show];
【讨论】:
以上是关于将 UIImage 添加到 UIAlertView 未按预期工作的主要内容,如果未能解决你的问题,请参考以下文章
将 UIActivityIndicatorView 添加到 UIAlertView
将 UItextField 和 UITextView 添加到 UIAlertView