开发者

When a subview is removed, remove from superview

I am trying to do something very similar to How to tell when a subView is removed a UIView

I add a view (A) as a subview, this in turn creates a subview (B) for itself. What it want:

When A's subview B is removed from A --> Remove A from it's superview.

I have subclassed UIView and tried to use - (void)willRemoveSubview:(UIView *)subview that in turn calls a method on the superview to remove this view. But it isn't working and I think it might be because B is in the process of being removed.

The above thread recommends using protocols, which I understand and use in my app already, but in this case I am not sure how to use it in order to do what I want and cannot find the correct re开发者_如何学Cference in the Apple Dev resources.

Could you help me in using a protocol & delegate to solve this problem?

Thanks


This works for me:

- (void)willRemoveSubview:(UIView *)subview {
    [self removeFromSuperview];
}

But if you want to use a protocol & delegate you could do so like this:

CustomView.h

@class CustomView;

@protocol CustomViewDelegate <NSObject>
- (void)customViewIsReadyToRemove:(CustomView *)customView;
@end

@interface CustomView : UIView {
}
@property (nonatomic, assign) IBOutlet id <CustomViewDelegate> delegate;
@end

CustomView.m

@implementation CustomView
@synthesize delegate;

- (void)willRemoveSubview:(UIView *)subview {
    [self.delegate customViewIsReadyToRemove:self];
}
@end

ContainerView.h

@interface ContainerView : UIView {
}
@property (nonatomic, retain) IBOutlet UIView *customView;
@end

ContainerView.m

@implementation ContainerView
@synthesize customView;

- (void)dealloc {
    self.customView.delegate = nil;
    self.customView = nil;
    [super dealloc];
}

- (void)customViewIsReadyToRemove:(CustomView *)customView {
    [customView removeFromSuperview];
}
@end

This example uses IBOutlets so you can use IB connect the container's customView property and the custom view's delegate property.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜