开发者

How to remove a subview if triggered from one of its components?

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 buttonWithT开发者_运维百科ype...

[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:

@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];


It should work.

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

Post the entire code of the initiation and the removeFromSuperview.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜