Iphone 删除以编程方式添加的UIImageView

Iphone 删除以编程方式添加的UIImageView,iphone,xcode,uiimageview,removeall,Iphone,Xcode,Uiimageview,Removeall,我正在制作一个程序,在主视图中有两个按钮 一个叫show,另一个叫hide 当用户按show按钮时,屏幕上会添加一个imageview 代码: -(IBAction)show{ UIImageView *img = [[UIImageView alloc] initWithFrame:CGRectMake(10, 10, 155, 155)]; img.image = [UIImage imageNamed:@"icon.png"]; [self.view addSubview:im

我正在制作一个程序,在主视图中有两个按钮

一个叫show,另一个叫hide

当用户按show按钮时,屏幕上会添加一个imageview

代码:

-(IBAction)show{
  UIImageView *img = [[UIImageView alloc] initWithFrame:CGRectMake(10, 10, 155, 155)];
  img.image = [UIImage imageNamed:@"icon.png"];
  [self.view addSubview:img];
}
当用户按下隐藏按钮时,我希望应用程序隐藏刚刚添加的图像(img)

但是

当我使用

-(IBAction)add{
  [img removeFromSuperView];
}
Xcode显示“img未清除”

编辑:有人说将对象定义为公共对象(@property),但问题是imageview只添加了一次。但我想让它在用户每次按下Show按钮时添加新的imageview


因此,我使用[[self-subviews]objectAtIndex:xx]removeFromSuperview]方法解决了这个问题

让这个UIImageView成为UIViewController类的成员

你的img对象只在show方法中可见,不在外部..这就是原因。在外面声明它,你的问题就会解决。

为你的图像视图设置一个
标签,然后你就可以通过这个标签获得它

[img setTag:123];

...

[[self.view viewWithTag:123] removeFromSuperview];

.h
文件中创建
UIImageView
的对象,如下图所示

UIImageView *img;
- (void)viewDidLoad
{
    ///your another code
    img = [[UIImageView alloc] initWithFrame:CGRectMake(10, 10, 155, 155)];
    img.image = [UIImage imageNamed:@"icon.png"];
    img.hidden = YES;
    [self.view addSubview:img];
}
-(IBAction)add{
    img.hidden = YES;
}
.m
文件
viewDidLoad:
方法中,只需像下面那样添加它

UIImageView *img;
- (void)viewDidLoad
{
    ///your another code
    img = [[UIImageView alloc] initWithFrame:CGRectMake(10, 10, 155, 155)];
    img.image = [UIImage imageNamed:@"icon.png"];
    img.hidden = YES;
    [self.view addSubview:img];
}
-(IBAction)add{
    img.hidden = YES;
}
当显示按钮按下时,显示图像

-(IBAction)show{
    img.hidden = NO;
    [self.view bringSubviewToFront:img];
}
对于隐藏,就像咆哮一样隐藏

UIImageView *img;
- (void)viewDidLoad
{
    ///your another code
    img = [[UIImageView alloc] initWithFrame:CGRectMake(10, 10, 155, 155)];
    img.image = [UIImage imageNamed:@"icon.png"];
    img.hidden = YES;
    [self.view addSubview:img];
}
-(IBAction)add{
    img.hidden = YES;
}

这里出现此错误是因为您没有为整个类定义img。这里您可以在show方法中访问此变量,因为此变量的作用域仅限于show方法/Users/PoriaX/Desktop/toMake/Classes/toMakeViewController。m:16:0/Users/PoriaX/Desktop/toMake/Classes/toMakeViewController。m:16:警告:“UIView”可能没有响应到“-removeFromSuperView”@user1846654哦,这是
removeFromSuperView
,而不是
removeFromSuperView
。FYI-Xcode 12,在2021年-当隐藏切换到“是”时,此解决方案仍然有效(我有多个视图控制器-在1中工作,在2中不会)。再次感谢,@Kjulyany关于这个主题的教程?Paras的方法绝对正确。您可以将
UIImageView*img
放在
{}
界面后面,如下所示:
@interface ClassName{UIImageView*img;}
或将其作为
@property(强,非原子)UIImageView*img和参考
img
self.img
@KKendall yes dude你也是对的,但我使用简单的流程,因为用户想隐藏和显示图像,点击按钮,否则你的逻辑也是对的dude。。。Thanx:)啊,我明白了。我只是不明白两者之间的区别,实际上我只是在这里问了一个问题。所以,不要将它设置为@property或作为#import语句下面的全局变量。