gpt4 book ai didi

ios - 如何通知 subview 删除的 super View

转载 作者:塔克拉玛干 更新时间:2023-11-02 09:01:06 25 4
gpt4 key购买 nike

我向 UIViewController 添加了自定义 UIView,在 View 中添加了一些代码后,我想从 UIViewController 中删除该 View ,但我不确定如何通知 UIViewController UIView 已删除。

我正在使用这个方法从 UIView 中退出

-(void)exit{
[self removeFromSuperview];
}

我需要设置监听器吗?感谢任何帮助


我发布了详细的解决方案。感谢 Rage、Bill L 和 FreeNickname

最佳答案

既然把代码写成注释不方便,那我就写成答案吧。这个答案说明了@Rage 在他的回答中的建议。

首先,您为CustomView 创建一个@protocol 并为其添加一个delegate。您声明 delegate 应遵守此协议(protocol)。然后在您的 ViewController 中实现您的协议(protocol)并将 ViewController 设置为您的 CustomView 的委托(delegate)。

像这样:

自定义 View .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

自定义 View .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

关于ios - 如何通知 subview 删除的 super View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32896648/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com