约束动画不正确

时间:2017-10-26 18:41:03

标签: ios objective-c uiview nslayoutconstraint

我创建了uiview自定义类并在主视图控制器中实现

-(KPHomeChartCategory *)chartCategory {

    if (!_chartCategory) {
    _chartCategory = [[KPHomeChartCategory alloc] init];
    _chartCategory.delegate = self;
    _chartCategory.translatesAutoresizingMaskIntoConstraints = NO;
    [self addSubview:_chartCategory];

    [self.chartCategory.topAnchor constraintEqualToAnchor:self.topAnchor constant:-7.5].active = YES;
    [self.chartCategory.rightAnchor constraintEqualToAnchor:self.rightAnchor].active = YES;

    self.chartCategoryLeftAnchor = [self.chartCategory.leftAnchor constraintEqualToAnchor:self.rightAnchor];
    self.chartCategoryLeftAnchor.active = YES;

    [self.chartCategory.heightAnchor constraintEqualToConstant:100].active = YES;

    }
    return _chartCategory;
}

我以这种方式动画uiview自定义类(KPHomeChartCategory)约束

-(void)openPanelTagAnimation {

    self.chartCategoryLeftAnchor.active = NO;
    self.chartCategoryLeftAnchor = [self.chartCategory.leftAnchor constraintEqualToAnchor:self.rightAnchor constant:-self.frame.size.width +105];
    self.chartCategoryLeftAnchor.active = YES;

    [UIView animateWithDuration:.6 delay:0 usingSpringWithDamping:1 initialSpringVelocity:1 options:UIViewAnimationOptionCurveEaseOut animations:^{
        self.customSwitch.alpha = 0;
        [self layoutIfNeeded];
    } completion:nil];
}

现在,如果你看一下视频,你会注意到我第一次展示customView时,我的集合视图从上面显示,但之后动画似乎非常简单......你能让我理解为什么会这样吗?

视频链接
  VIDEO ANIMATION

为什么我的动画首先从上到下开始,然后才是线性的? (从右到左的线性动画是正确的,应该是第一次动画自定义视图)

1 个答案:

答案 0 :(得分:1)

在您发布的动画中,单元格是动画的,因为它们的初始大小为CGSizeZero或某个接近该值的值,然后集合视图布局无效,因此它们的大小会增加。您可以通过设置集合视图的transform属性的动画来避免这种情况。这就像解决你提到here的问题一样。例如,在一个简单的演示中,我可以通过将顶部,左侧和右侧固定到具有恒定高度的超级视图来放置集合视图。我以编程方式设置单元格大小:

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    return CGSizeMake(collectionView.bounds.size.width / 3.0, collectionView.bounds.size.height);
} 

然后我使用CGAffineTransform将集合视图移出屏幕。例如:

- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    self.collectionView.transform = CGAffineTransformTranslate(CGAffineTransformIdentity, self.view.bounds.size.width, 0.0);
}

最后,当我想要执行动画时,我将变换设置回其标识:

- (void)animate {
    // Reversing and repeating for the sake of testing
    [UIView animateWithDuration:0.5 delay:0.0 options:UIViewAnimationOptionRepeat | UIViewAnimationOptionAutoreverse animations:^{
        self.collectionView.transform = CGAffineTransformIdentity;
    } completion:nil];
}

使用此方法可确保单元格大小始终相同,因此在动画块中的约束发生变化时不会生成动画。

当我在我的演示项目中更改约束时,这是动画,请注意初始动画中单元格大小的变化。

enter image description here

设置transform时的相同动画:

enter image description here