0

Is there a notification or callback when a UIView is added in other UIView which has a UIViewController. We can get a UIView's ViewController, if it has one, via nextResponder. (Reference)

But depending on nextResponder is not reliable, if the UIView is not been added into a View which has ViewController, this method fails. For example, when we are calling from the cell's responder in UITableViewDataSource's cellForRowAtIndexPath. Because by the time of calling cellForRowAtIndexPath, the cell being dequeued hasn't been added into UITableView yet. However, we can call that method in - tableView:willDisplayCell:forRowAtIndexPath:, because by the time of calling - tableView:willDisplayCell:forRowAtIndexPath:, the cell is already being added into TableView.

Community
  • 1
  • 1
Zitao Xiong
  • 956
  • 1
  • 10
  • 18

1 Answers1

0

So if you have ViewA which is the view of ViewControllerA and you want to add the ViewB you can subclass ViewB

@protocol ViewBDelegate

- (void) viewAddedToSuperview:(ViewB*)sender;

@end

@interface ViewB: UIView

@property (nonatomic, assign) id< ViewBDelegate > delegate;

@end
@implementation

- (void)didMoveToSuperview {
    [super didMoveToSuperview];
    [delegate viewAddedToSuperview:self];
}


@end

and in ViewControllerA you implements the protocol ViewBDelegate.

This is just an example of my idea.

Let me know in the comments it is can help you, otherwise I will try to propose other solutions depending on your goals.

Marco Santarossa
  • 4,058
  • 1
  • 29
  • 49
  • Thanks for the answer. This is probably not I am looking for. Maybe there is no perfect solution for this. My problem is that when my 'View' is being added as a subview of some 'View'(as: 'ViewSuper'). If this 'ViewSuper' does not have a UIViewController AND none of 'ViewSuper''s super views has a UIViewController, I don't want to get called. In your case, if ViewA is not the view of a `ViewController`, didMOveToSuperview still get called. – Zitao Xiong Aug 10 '16 at 22:58