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.)
The best pattern for this type of action is the “delegate” pattern.
You can subclass anything and add this property:
for the instance variable:
Also, define a protocol like this:
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:
The viewcontroller then can say something like: