从其他 ViewController 中删除带有标记的视图

slo*_*o95 1 objective-c selector subview uiview ios

我一直试图从其他人调用的操作中删除我的视图,ViewController但我不知道该怎么做这是我的代码:

 + (Menu *)Mostrar:(UIView *)view{
     CGRect IMGFrame = CGRectMake( 5, 20, 70, 70 );
     UIButton *boton=[[UIButton alloc] initWithFrame:IMGFrame];
     [boton setBackgroundImage:[UIImage imageNamed:@"Logo_SuperiorBTN.png"] forState:UIControlStateNormal];
     [boton setBackgroundImage:[UIImage imageNamed:@"Logo_SuperiorBTN.png"] forState:UIControlStateSelected];
     [boton addTarget: self action: @selector(cerrarmenu:) forControlEvents: UIControlEventTouchUpInside];
     [boton setTag:899];
     [view addSubview: boton];
}
Run Code Online (Sandbox Code Playgroud)

那部分是从我MainViewController这样调用的

-(IBAction)menu:(id)sender{
    Menu *hudView = [Menu Mostrar:self.view];
}
Run Code Online (Sandbox Code Playgroud)

然后它显示视图,当我尝试使用按钮关闭它时它崩溃了

关闭菜单的代码是

+(void)cerrarmenu:(UIView *)view{
    for (UIView *subView in view) {
        if (subView.tag == 899) {
            [subView removeFromSuperview];
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

谢谢圣地亚哥

Bri*_*acy 5

在最后的代码块中,UIView您用作循环迭代器和调用的实例subview实际上并不代表view. 这是您应该如何更改它。

+(void)cerrarmenu:(UIView *)view {
    for (UIView *subView in view.subviews) {    // UIView.subviews
        if (subView.tag == 899) {
            [subView removeFromSuperview];
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

这利用@property(nonatomic, readonly, copy) NSArray *subviewsUIView.

  • 他将Target:self 添加到cerrarmenu。所以观点=自我。-> 他无法通过这种方式从超级视图中删除所有视图。唯一的方法是为此 customView 使用委托 (2认同)