37
CustomView *customView = [...];
[self.view addSubview:customView];

I need to detect in my CustomView class when it is added in other views or when my superview changes.

Jeremy Grenier
  • 674
  • 1
  • 6
  • 8

3 Answers3

81

You can use willMoveToSuperview: and didMoveToSuperview to detect when the view is moved around. layoutSubviews will be called when the superview changes frame.

mackworth
  • 5,873
  • 2
  • 29
  • 49
Hampus Nilsson
  • 6,692
  • 1
  • 25
  • 29
  • Thanks a lot, I had not thought of layoutSubviews. – Jeremy Grenier Jul 19 '12 at 10:08
  • Question: in my view controller, `viewWillAppear:animated` is called *before* `viewWillLayoutSubviews`. So even if I use `viewWillLayoutSubviews` to arrange my views based on the superview's size, I cannot start some animations *after that* in `viewWillAppear:animated` where they belong. How should this be done? – Timo Jun 20 '13 at 14:32
  • 2
    Second method name is `didMoveToSuperview` (without the `:`), just in case anyone copy/pastes. – M-P May 04 '15 at 22:55
7
  • For a UIView use - (void)didMoveToSuperview
  • For a UIViewController use -(void)viewWillAppear:(BOOL)animated
Peter
  • 1,061
  • 1
  • 13
  • 20
-5

also assign THE TAG of Customview before addsubview and the detect by Particular TAG.

Ashok Domadiya
  • 1,124
  • 13
  • 31
  • Not a bad strategy if you want to keep track of the view from the superview's perspective with the `viewWithTag:` method, but that wasn't the question here. – turingtested Dec 19 '18 at 10:34