[英]How to notify superview of subview removal
我向UIViewController添加了一个自定义UIView,在视图中的一些代码之后,我想从UIViewController中删除这个视图,但是我不知道如何通知UIViewController UIView的删除。
我正在使用此方法从UIView中退出
-(void)exit{
[self removeFromSuperview];
}
我需要设置一个监听器吗? 任何帮助表示赞赏
我发布了详细的解决方案。 感谢Rage,Bill L和FreeNickname
使用委托。 将协议添加到自定义View,该协议实现了一种通知删除子视图的方法。 在添加自定义视图时使View控制器成为委托。 在自定义类中,在[self removeFromSuperview];
之前调用委托方法[self removeFromSuperview];
由于将代码编写为注释并不方便,我将把它写成答案。 这个答案说明了@Rage在他的回答中提出的建议。
首先,为CustomView
创建一个@protocol
并CustomView
添加delegate
。 您声明delegate
应符合此协议。 然后在ViewController中实现协议并将ViewController设置为CustomView的委托。
像这样:
CustomView.h:
@protocol CustomViewDelegate<NSObject>
//You can also declare it as @optional. In this case your delegate can
//ignore this method. And when you call it, you have to check, whether
//your delegate implements it or not.
-(void)viewWasRemoved:(UIView *)view
@end
@interface CustomView: UIView
@property (nonatomic, weak) id<CustomViewDelegate> delegate;
@end
CustomView.m:
@implementation CustomView
-(void)exit {
[self removeFromSuperview];
//if your method is NOT @optional:
[self.delegate viewWasRemoved:self];
//if it IS @optional:
if ([self.delegate respondsToSelector:@selector(viewWasRemoved:)]) {
[self.delegate viewWasRemoved:self];
}
}
@end
ViewController.m:
#import "CustomView.h"
@interface ViewController()<CustomViewDelegate>
@end
@implementation ViewController
-(void)someMethod {
self.customView.delegate = self;
}
-(void)viewWasRemoved:(UIView *)view {
//Whatever
}
@end
使用名为viewWasRemoved:
的方法或类似的方法为它设置委托。 将视图的委托设置为要通知的ViewController,然后在exit方法中调用[self.delegate viewWasRemoved:self];
,然后将启动ViewController中的viewWasRemoved:
方法,您可以在删除视图后执行相关的任何相关工作。
我将发布一个详细的解决方案,以防它帮助任何人,或任何人可以提供任何指针。 谢谢Rage,Bill L和FreeNickname:
答案是使用委托
首先我将superview导入到我的子视图的.h中:
#import "ViewController.h"
然后我将一个委托ID添加到同一个文件中:
@property (weak) id delegate;
然后在superview中初始化自定义UIView时,我设置了委托:
CustomView *view = [[CustomView alloc]initWithFrame:frame];
view.delegate = self;
我在superview中添加此方法以进行回调:
- (void) viewWasRemoved: (UIView *) view{
NSLog(@"removed");
}
然后最后在我的subView中调用该方法:
-(void)exit{
[self.delegate viewWasRemoved:self];
[self removeFromSuperview];
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.