约束动画不正确

Constraints animation is incorrect

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

-(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 自定义 class (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 时,我的集合视图是从上方显示的,但之后动画似乎非常简单......你能让我明白为什么会这样吗事情?

视频Link
VIDEO ANIMATION

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

在您发布的动画中,单元格正在动画,因为它们的初始大小为 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];
}

使用此方法可确保单元格始终具有相同的大小,因此当动画块中的约束发生变化时不会进行动画处理。

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

设置transform时相同的动画: