testing
testing

Reputation: 20279

willMoveToSuperview is called twice

I'm adding a view to my view controller. In this view I have implemented willMoveToSuperview. Now I experienced that this function is called twice:

  1. When the view is added to the superview (as intended)
  2. When the current view controller is dismissed (e.g. a new view controller is pushed on the stack of the navigation controller)

Is this the intended behavior? What other method could I use to detect if the current view is added to a superview only? didMoveToSuperview seems to do the same. Or should I use a variable which remembers how often the function is called?

Edit:

Now I think I found the reason why it is called twice. I'm using a hide method to dismiss the view. It's in C# but it shouldn't matter here:

UIView.Animate (
    0.5, // duration
    () => { Alpha = 0; },
    () => { RemoveFromSuperview(); }
);

If I comment this out it isn't called twice. How can I keep the animation and assure that it is only called once?

Upvotes: 0

Views: 2291

Answers (1)

rob mayoff
rob mayoff

Reputation: 385600

When a view is added to a superview, the system sends willMoveToSuperview: to the view. The parameter is the new superview.

When a view is removed from a superview, the system sends willMoveToSuperview: to the view. The parameter is nil.

You can't prevent the system from sending willMoveToSuperview: when you remove the view from its superview, but you can check the parameter:

- (void)willMoveToSuperview:(UIView *)newSuperview {
    if (newSuperview != nil) {
        // not a removeFromSuperview situation
    }
}

Upvotes: 7

Related Questions