在动画重新定位其他视图后从其超级视图中删除视图

时间:2014-03-21 11:54:38

标签: ios objective-c animation

我的应用模拟扑克牌游戏。我的控制器中有一个名为gridView的视图,其中包含16个卡片视图。卡片视图已经定位在网格视图内(它是绿色的)没有任何布局约束:

enter image description here

现在在游戏的某个时刻,我需要为两个卡片视图设置动画,将它们移到屏幕边界之外,并在动画完成后,我需要从它的超视图(网格视图)中删除它们。但我需要不是同时做这个,而是每次都有一个视图,所以我使用动画,当它完成时触发另一个。

我使用两个数组:cardViews包含网格视图中的所有卡片视图,但不包含需要通过动画移除的卡片视图,这些视图包含在matchedCardViews中。所以我写了这个方法:

- (void) animateMatchedCardViews {
    if(self.matchedCardViews.count) {
        UIView* view= self.matchedCardViews.firstObject;
        [UIView animateWithDuration:1.0 delay:0.0 options:UIViewAnimationOptionCurveEaseIn animations:^{
            view.frame= aFrameOutOfScreenBounds;  // I checked out: the frame is computed
                                                  // correctly, converted in grid view's
                                                  // coordinates
        } completion:^(BOOL finished) {
            [view removeFromSuperview];
            [self.matchedCardViews removeObject:view];
            // I recursively call the method to remove the other card
            // in self.matchedCardViews. 
            [self animateMatchedCardViews];
        }];
    }
}

但是从它的超视图中移除视图会弄乱一切:第一个动画顺利进行,我看到视图慢慢走出屏幕,但第二个动画完全错误:所有其他视图我不知道为什么是布局再次,在错误的位置,应该动画的第二张卡片视图不会移动到屏幕外的某个点,而是在网格视图内。红色圆圈中的视图移动到错误的位置:

enter image description here

PS:如果我没有拨打[view removeFromSuperview]行所有修复,但我需要将其从超级视图中删除。

2 个答案:

答案 0 :(得分:0)

试试这个,

- (void) animateMatchedCardViews {
    if(self.matchedCardViews.count) {
        UIView* view= self.matchedCardViews.firstObject;
        [UIView animateWithDuration:1.0 delay:0.0 options:UIViewAnimationOptionCurveEaseIn animations:^{
            view.frame= aFrameOutOfScreenBounds;  // I checked out: the frame is computed
                                              // correctly, converted in grid view's
                                              // coordinates
        } completion:^(BOOL finished) {
           if (finished) {
               [view removeFromSuperview];
               [self.matchedCardViews removeObject:view];
               // I recursively call the method to remove the other card
               // in self.matchedCardViews. 
               [self animateMatchedCardViews];
           }

        }];
    }
}

答案 1 :(得分:0)

似乎xcode想要自动为没有指定约束的视图添加约束,如果我使用autolayout:

enter image description here

可能它解决了歧义,但在我的情况下没有任何歧义,因为我手动将视图放在网格视图中。

我发现的解决方案是子类UIView并覆盖addConstraint:addConstraints:,而不调用超类实现,以便不会真正添加约束。这完美无缺,没有任何崩溃。

- (void) addConstraint:(NSLayoutConstraint *)constraint {
}

- (void) addConstraints:(NSArray *)constraints {
}