首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >NSLayoutConstraint动画在iOS 10-11上的发行

NSLayoutConstraint动画在iOS 10-11上的发行
EN

Stack Overflow用户
提问于 2018-03-09 12:22:42
回答 1查看 274关注 0票数 0

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

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

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

动画代码:

代码语言:javascript
复制
#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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-03-09 13:09:05

试一试它在iOS 9,10,11中工作

目标C

代码语言:javascript
复制
- (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

代码语言:javascript
复制
@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()
        })
    }
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/49193750

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档