我有一个名为
ProgressBarView
的父 UIView。在里面,我设置了一个名为 progressForeground
的 UIView,负责显示进度条的实际百分比。我希望 progressForeground
能够根据其设置的宽度约束进行动画处理。这就是我设置视图的方式:
UIView *progressForeground = [[UIView alloc] init];
[self addSubview:progressForeground];
progressForeground.translatesAutoresizingMaskIntoConstraints = NO;
[progressForeground.heightAnchor constraintEqualToConstant:frame.size.height].active = YES;
progressForeground.backgroundColor = [UIColor colorWithWhite:1.0 alpha:1.0];
[progressForeground.leadingAnchor constraintEqualToAnchor:progressBackground.leadingAnchor].active = YES;
[progressForeground.centerYAnchor constraintEqualToAnchor:progressBackground.centerYAnchor].active = YES;
progressForeground.layer.cornerRadius = 5;
设置必要的约束后,我添加了宽度约束并在动画块内更改了其值,如下所示:
NSLayoutConstraint *progressForegroundWidthConstraint = [NSLayoutConstraint constraintWithItem:progressForeground
attribute:NSLayoutAttributeWidth
relatedBy:NSLayoutRelationEqual
toItem:nil
attribute:NSLayoutAttributeNotAnAttribute
multiplier:1.0
constant:0
];
progressForegroundWidthConstraint.active = YES;
[self layoutIfNeeded];
[UIView animateWithDuration:5
animations:^{
progressForegroundWidthConstraint.constant = 60;
[self layoutIfNeeded];
}
];
正如here提到的,我确保在父视图上调用
layoutIfNeeded
方法来刷新任何挂起的动画。
我希望
progressForegroundView
的宽度会随着动画而变化,但它只是直接跳转到 60 的值,没有任何动画。这是怎么回事?
我尝试为progressForegroundView设置动画,但是它只跳转到指定值,没有任何动画
通过在调用
[self setNeedsLayout]
后添加 [self layoutIfNeeded]
来修复此问题。
[self layoutIfNeeded];
[self setNeedsLayout];
[UIView animateWithDuration:1.5
animations:^{
progressForegroundWidthConstraint.constant = progressBarWidth * progressPercentage / 100;
[self layoutIfNeeded];
}
];