iOS 10-11上的NSLayoutConstraint动画问题

时间:2018-03-09 12:22:42

标签: ios objective-c animation autolayout nslayoutconstraint

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

enter image description here

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

enter image description here

这在iOS 10-11上发生:

enter image description here

动画代码:

#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

修改

感谢@Kuldeep。只是强调:重点是至少在层次结构中上层受影响视图的超级视图中调用layoutIfNeeded。所以在我的情况下,由于containerView的高度也在变化,我不得不在layoutIfNeeded的超级视图上调用containerView

1 个答案:

答案 0 :(得分:1)

试试这个适用于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()
        })
    }
}