【问题标题】:When a subview is removed, remove from superview当子视图被移除时,从父视图中移除
【发布时间】:2011-08-06 22:22:11
【问题描述】:

我正在尝试做一些与How to tell when a subView is removed a UIView非常相似的事情

我添加了一个视图 (A) 作为子视图,这反过来又为自己创建了一个子视图 (B)。它想要什么:

当 A 的子视图 B 从 A 中移除时 --> 从它的父视图中移除 A。

我对 UIView 进行了子类化,并尝试使用 - (void)willRemoveSubview:(UIView *)subview 来调用父视图上的方法来删除此视图。但它不起作用,我认为这可能是因为 B 正在被删除。

上面的线程建议使用协议,我已经理解并在我的应用程序中使用了这些协议,但在这种情况下,我不确定如何使用它来做我想做的事情,并且在 Apple Dev 资源中找不到正确的参考.

您能帮我使用协议和委托来解决这个问题吗?

谢谢

【问题讨论】:

    标签: iphone objective-c ios uiview protocols


    【解决方案1】:

    这对我有用:

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

    但如果你想使用协议和委托,你可以这样做:

    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
    

    此示例使用 IBOutlets,因此您可以使用 IB 连接容器的 customView 属性和自定义视图的 delegate 属性。

    【讨论】:

    • 太棒了!感谢您详尽的回答。我将在一周内完成这个,看看我是否可以让它工作。
    猜你喜欢
    • 1970-01-01
    • 2013-10-01
    • 2011-10-09
    • 1970-01-01
    • 1970-01-01
    • 2021-03-05
    • 1970-01-01
    • 2012-01-23
    • 2013-02-02
    相关资源
    最近更新 更多