如何以编程方式显示视图 - 使用" x"按钮关闭视图?

时间:2014-05-29 18:36:21

标签: ios objective-c

我正在尝试以编程方式显示包含图像和" x"按钮 - 在代码中标记为* btnDismiss - 关闭视图。

这是我的问题: 代码将成功显示图像和" x"按钮。但是,单击" x"按钮当前不关闭视图 - 图像和" x"按钮保持可见。

我是xCode的新手,所以请提供详细的回复(如果你遗漏了答案,我可能无法填补空白!)

注意:如果您有另一种解决方案,可以使用" x"来显示imageView。按钮同时生成imageView和" x"按钮消失,也欢迎。

这是我的代码:

#import "XYZViewController.h"

@interface XYZViewController ()

@end

@implementation XYZViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    UIViewController *vc = [[UIViewController alloc] init];
    [self presentViewController:vc animated:YES completion:nil];

    UIImageView *bgImage = [[UIImageView alloc] initWithFrame:CGRectMake(5, 5, 200, 200)];
    bgImage.image = [UIImage imageNamed:@"image"];
    [self.view addSubview:bgImage];

    UIButton *btnDismiss = [[UIButton alloc] initWithFrame:CGRectMake(10, 10, 100, 100)];
    [btnDismiss setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [btnDismiss setTitle:@"x" forState:UIControlStateNormal];
    [btnDismiss addTarget:self action:@selector(dismissVC:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:btnDismiss];
}

-(void)dismissVC:(id)sender {
    [self dismissViewControllerAnimated:YES completion:nil];
}

提前致谢!

2 个答案:

答案 0 :(得分:0)

您的代码设置为关闭以模态方式呈现的视图控制器。但您要删除的视图是self.view

的子视图

您可以删除UIImageViewUIButton,并在删除方法中调用removeFromSuperview。使用此方法,您无需显示或关闭其他视图控制器。

-(void)removeViews:(id)sender {
    [self.xButton removeFromSuperview];
    [self.imageView removeFromSuperview];
}

编辑以回复评论

您需要为xButton和imageView

声明属性
@property UIButton *xButton;
@property UIImageView *imageView;

编辑以显示完整代码

@interface MJNViewController ()
@property UIButton *xButton;
@property UIImageView *imageView;
@end

@implementation MJNViewController

- (void)viewDidLoad
{
    [super viewDidLoad];

    self.imageView = [[UIImageView alloc] initWithFrame:CGRectMake(5, 5, 200, 200)];
    self.imageView.image = [UIImage imageNamed:@"myImage"];
    [self.view addSubview:self.imageView];

    self.xButton = [[UIButton alloc] initWithFrame:CGRectMake(10, 10, 100, 100)];
    [self.xButton setTitle:@"x" forState:UIControlStateNormal];
    [self.xButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [self.xButton addTarget:self action:@selector(removeViews:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.xButton];
}

-(void)removeViews:(id)sender
{
    [self.imageView removeFromSuperview];
    [self.xButton removeFromSuperview];
}

@end

答案 1 :(得分:0)

您需要另外UIViewController出示XYZViewController才能使-dismissViewControllerAnimated:正常工作。

来自Apple Docs:

  

呈现视图控制器负责解除它所呈现的视图控制器。如果在呈现的视图控制器本身上调用此方法,它会自动将消息转发给呈现视图控制器。

由于没有显示视图控制器,因此调用-dismissViewControllerAnimated:对您无效。