我正在尝试为视图实现显示/隐藏动画。其想法是调整视图的高度约束大小,并让它的superview与它一起调整大小。为此,我添加了视图的高度约束,并将其底部约束固定到superview的底部(因此我不需要指定superview的高度约束)

在iOS 9上,它按预期工作:

这种情况发生在iOS 10-11上:

动画代码:
#import "ViewController.h"
@interface ViewController ()
{
BOOL _hideFlag;
CGFloat _redViewHeight;
}
@property (strong, nonatomic) IBOutlet UIView *containerView;
@property (strong, nonatomic) IBOutlet UIButton *toggleButton;
@property (strong, nonatomic) IBOutlet UIView *redView;
@property (strong, nonatomic) IBOutlet NSLayoutConstraint *redViewHeightConstraint;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
[_toggleButton addTarget:self action:@selector(toggle:) forControlEvents:UIControlEventTouchUpInside];
_redViewHeight = _redViewHeightConstraint.constant;
}
- (void)toggle:(UIButton *)sender
{
_hideFlag = !_hideFlag;
[_containerView layoutIfNeeded];
[UIView animateWithDuration:0.2 animations:^{
_redViewHeightConstraint.constant = _hideFlag ? 0 : _redViewHeight;
[_containerView layoutIfNeeded];
}];
}
@end编辑
多亏了库尔迪普。强调一下:重点是至少在受影响的上层视图的层次结构中调用layoutIfNeeded。因此,在我的例子中,由于containerView的高度也在变化,我不得不在containerView的superview上调用layoutIfNeeded。
发布于 2018-03-09 13:09:05
试一试它在iOS 9,10,11中工作
目标C
- (IBAction)btnChangeTapped:(UIButton *)sender {
sender.selected =! sender.selected;
if (sender.selected) {
[self.view layoutIfNeeded];
[UIView animateWithDuration:1.0 animations:^{
self.constraintHeightOfView.constant = 100.0; // as per your require
[self.view layoutIfNeeded];
}];
}
else {
[self.view layoutIfNeeded];
[UIView animateWithDuration:1.0 animations:^{
self.constraintHeightOfView.constant = 350.0; // Back to Normal
[self.view layoutIfNeeded];
}];
}
}Swift 5.0
@IBAction func btnChangeTapped(_ sender: UIButton) {
sender.isSelected = !sender.isSelected
if sender.isSelected {
self.view.layoutIfNeeded()
UIView.animate(withDuration: 1.0, animations: {
self.constraintHeightOfView.constant = 100.0 // as per your require
self.view.layoutIfNeeded()
})
} else {
self.view.layoutIfNeeded()
UIView.animate(withDuration: 1.0, animations: {
self.constraintHeightOfView.constant = 350.0 // Back to Normal
self.view.layoutIfNeeded()
})
}
}https://stackoverflow.com/questions/49193750
复制相似问题