在基于约束的视图中,有几个标签(顶部),按钮(底部)和一个自定义的UIView子类(检查器),它由许多CALayer组成。
我试图通过删除和添加约束来为视图的大小设置动画:
// self.containerWidth is a constraint instance
// from Interface Builder Outlet, which is set to
// constrain the width of the whole view.
[self.calendarContainer removeConstraint:self.containerWidth];
[UIView animateWithDuration:4.0 animations:^{
[self.calendarContainer addConstraint:
[NSLayoutConstraint constraintWithItem:self.calendarContainer
attribute:NSLayoutAttributeWidth
relatedBy:NSLayoutRelationEqual
toItem:self.view
attribute:NSLayoutAttributeWidth
multiplier:0
constant:700]];
[self.calendarContainer layoutIfNeeded];
}];
动画完成后,视图如下所示:
在动画期间,标签(顶部)和按钮(底部)根据上面给出的持续时间平滑移动,然而,在任何其他转换发生之前,检查器视图很快地弹回到最终状态。 /强>
我怀疑某些内容与某些CATransaction混杂在一起。
在检查器视图中,我重新排列了-layoutSubviews
中的图层框架:
- (void)layoutSubviews {
[super layoutSubviews];
if (!self.layer.sublayers.count) {
[self prepareLayers];
}
int rowCount = [self rowCount];
CGFloat rowHeight = [self rowHeight];
[self.layer.sublayers enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
CALayer *rowLayer = obj;
NSNumber *rowIndex = [rowLayer valueForKey:@"rowindex"];
if (rowIndex) {
NSUInteger rowIndexValue = rowIndex.integerValue;
if (rowIndexValue < rowCount) {
rowLayer.hidden = NO;
rowLayer.frame = CGRectMake(0, rowHeight * rowIndexValue, self.frame.size.width, rowHeight);
[rowLayer.sublayers enumerateObjectsUsingBlock:^(id obj2, NSUInteger idx2, BOOL *stop2) {
CALayer *cellLayer = obj2;
NSUInteger colIndex = [[cellLayer valueForKey:@"cellindex"] integerValue] - rowIndexValue * 7 - 1;
cellLayer.frame = CGRectMake(colIndex*self.frame.size.width/7, 0, self.frame.size.width/7, rowHeight);
}];
} else {
// hide
rowLayer.hidden = YES;
}
}
}];
}
如何更正这些动画?
BTW,推荐插入这些图层重新定位代码的最佳位置在哪里?答案 0 :(得分:2)
似乎效果是由图层的隐式动画产生的。
以下代码可能会修复所有动画不匹配。
NSTimeInterval duration = 4.0;
[UIView animateWithDuration:duration animations:^{
[CATransaction begin];
[CATransaction setValue:@(duration)
forKey:kCATransactionAnimationDuration];
CAMediaTimingFunction *func = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
[CATransaction setAnimationTimingFunction:func];
[self.calendarContainer removeConstraint:self.containerWidth];
[self.calendarContainer addConstraint:[NSLayoutConstraint constraintWithItem:self.calendarContainer attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeWidth multiplier:0 constant:700]];
[self.calendarContainer layoutIfNeeded];
[CATransaction commit];
}];