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 reference 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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.