RemoveFromSuperView() with animation - AnimationWi

2019-05-21 02:34发布

问题:

I have a UIView and try to remove it from its superview using an animation (fading to alpha 0.0). Works fine but the view is never removed from the superview although I added a delegate to AnimationWillEnd. Here's the code. The console output is not written and the view is not removed. What's wrong?

    UIButton oBtn = UIButton.FromType(UIButtonType.RoundedRect);
    oBtn.Frame = new RectangleF(0, 0, 100, 20);
    oBtn.SetTitle("Hide", UIControlState.Normal);
    oBtn.Center = new PointF(80, 120);
    oBtn.TouchUpInside += delegate(object sender, EventArgs e) {
        UIView.BeginAnimations(null);

            UIView.AnimationWillEnd += delegate {
           Console.WriteLine("Removed.");
           oView.RemoveFromSuperview();
            };

    UIView.SetAnimationDuration(2);
    UIView.SetAnimationBeginsFromCurrentState(true);
    oView.Alpha = 0.0f;
    UIView.CommitAnimations();
   };
   oView.AddSubview(oBtn);

回答1:

I tried a lot of things with your code but it seems that the UIView.AnimationWillEnd handler never gets called. There is a way however, to perform the task you want:

oBtn.TouchUpInside += delegate(object sender, EventArgs e) {

        UIView.Animate(2, 
            delegate {
                oView.Alpha = 0.0f;
            },
            delegate {
                Console.WriteLine("Removed.");
                oView.RemoveFromSuperview();
            });
   };

The second anonymous method gets called when the animation completes. You can check Animate's other overloads for more options.



回答2:

The button needs to be defined outside of the scope of the method, otherwise it will get collected sooner than expected. Try defining the button at the class level, and then setting it to null in your AnimationWillEnd delegate.



标签: xamarin.ios