iOS使用约束实现动画效果

我知道的方法有两种:

1.在改变完约束后,在动画块内,使用方法layoutIfNeeded,可以实现一般普通的动画效果。

2.使用Facebook的pop框架,给约束加动画,实例代码如下(pop详情见:http://www.jianshu.com/p/1172578c96e1)。

#import "ViewController.h"

#import "Masonry.h"

#import "POP.h"


@interface ViewController ()


/*!*/

@property (nonatomic,strong) UILabel *label;


@end


@implementation ViewController


- (void)viewDidLoad {

    [super viewDidLoad];

    // Do any additional setup after loading the view, typically from a nib.

    

    [self label];

}

- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {

    [super touchesEnded:touches withEvent:event];

    NSLayoutConstraint *leftConstraint = nil;

    

//    POPSpringAnimation *positionAnimation = [POPSpringAnimation animationWithPropertyNamed:kPOPLayoutConstraintConstant];//kPOPLayerPositionY

    POPBasicAnimation *positionAnimation = [POPBasicAnimation animationWithPropertyNamed:kPOPLayoutConstraintConstant];

    for (NSLayoutConstraint *constraint in self.view.constraints) {

        if (constraint.firstItem == self.label && constraint.firstAttribute == NSLayoutAttributeLeft) {

            leftConstraint = constraint;

            break;

        }

    }

    positionAnimation.duration = 1;

    positionAnimation.fromValue = @(leftConstraint.constant);

    positionAnimation.toValue = @(0);

//    positionAnimation.springBounciness = 10;

    [positionAnimation setCompletionBlock:^(POPAnimation *anim, BOOL finished) {

        [_label mas_updateConstraints:^(MASConstraintMaker *make) {

            make.left.equalTo(self.view).offset(100);

        }];

    }];

    

    [leftConstraint pop_addAnimation:positionAnimation forKey:@"constantAnimation"];

}

- (void)didReceiveMemoryWarning {

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}

#pragma mark - Getter

- (UILabel *)label {

    if (! _label) {

        _label = [[UILabel alloc]init];

        _label.backgroundColor = [UIColor cyanColor];

        _label.text = @"what test123";

        [self.view addSubview:_label];

        [_label mas_makeConstraints:^(MASConstraintMaker *make) {

            make.left.equalTo(self.view).offset(300);

            make.top.equalTo(self.view).offset(100);

        }];

    }

    return _label;

}


@end


你可能感兴趣的:(iOS)