views:

27

answers:

2

I'm looking for a smart way to remove a subview (with removeFromSuperview) when the subview itself (or precisely said one of its components) triggered the removal. As for the source code this would be like

UIView * sub_view = [[[UIView alloc] initWith...

UIButton *button = [UIButton buttonWithType...

[sub_view addSubview:button];

[self.view addSubview:sub_view];

If the button have now something like

[button addTarget:self action:@selector(closeMySubview) forControlEvents:UIControlEventTouchUpInside];

the call to removeFromSuperview inside closeMySubview does not work but results in SIGABRT and unrecognized selector sent to instance ... . Well that there is something not more present anymore is not a surprise but what would be the right way?

(Removing the subview if triggered from an another gui component would work of cause but is not the point here.)

A: 

It should work.

Check if your sub-view points to an existing view.

Post the entire code of the initiation and the removeFromSuperview.

Michael Kessler
Yes, it sounds like there's a coding error in closeMySubview.
Seamus Campbell
A: 

The best pattern for this type of action is the "delegate" pattern.

You can subclass anything and add this property:

@property (assign) id delegate;

for the instance variable:

id delegate;

Also, define a protocol like this:

@protocol MySubViewDelegate

    -(void)myViewDidFinish:(UIView *)view;

So in your view controller, you can instantiate the subview, tell it your its delegate, and add it to the view. Then, an action on the subview calls the method:

[delegate myViewDidFinish:self];

The viewcontroller then can say something like:

[view removeFromSuperView];
DexterW
This works. I assume the key is that the call leading to removeFromSuperview must be coming from the very same view which should be removed?!
georgij
Yes, this makes the most sense logically. I like to think of it this way:Suppose I show you a watch. You look at it, and then decide you're finished. Who's job is it to put the watch away, mine, or the watch's?In this case, a view is showing you something. Therefore, it should be up to that view how and when to put it away!
DexterW