虽然使用Autolayout用了很久,但是都是在XIB和Storyboard上直接拖拽的约束。
对于一些要自定义的view的视图和动画就很难过了,之前一直在网上搜了很多都没有弄明白。最近查了好久总算实现了一个简单的动画。
背景:在xib或storyboard上拖拽一个UIButton,设置约束为水平居中+垂直居中+宽度100+高度100。
实现效果:点击按钮动画将这个按钮移动到,左边距50+上边距50+宽度100+高度100,再点击移动到,左边距150+上边距150+宽度100+高度100,可反复点击。
实现思路:删除在xib上拖拽的约束,如果不删除,控制台会给出约束冲突的提示。新定义约束给予赋值,注意每次赋值新的约束前需要将原有的约束删除,否则还是会提示约束冲突。
//
// MyTreeViewController.m
// LemonTree2
//
// Created by wdl on 14-10-8.
// Copyright (c) 2014年 wdl. All rights reserved.
//
@interface MyTreeViewController ()
@property(nonatomic,weak)IBOutlet UIButton *buttonAnimation;
@property(nonatomic,weak)IBOutlet NSLayoutConstraint *cs1;
@property(nonatomic,weak)IBOutlet NSLayoutConstraint *cs2;
@property(nonatomic,strong) NSMutableArray *csArray;
@property(nonatomic,assign) BOOL boolButtonAnimation;
@end
@implementation MyTreeViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
[self.view setBackgroundColor:[UIColor icebergColor]];
self.navigationController.navigationBarHidden = YES;
self.csArray = [NSMutableArray arrayWithCapacity:0];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(IBAction)animationButtonPress:(id)sender{
//删除相关的约束
[self.view removeConstraint:self.cs1];
[self.view removeConstraint:self.cs2];
[self.view removeConstraints:self.csArray];
[self.csArray removeAllObjects];
if (!self.boolButtonAnimation) {
[UIView transitionWithView:self.buttonAnimation
duration:1.0
options:UIViewAnimationOptionTransitionFlipFromTop
animations:^{
[self.buttonAnimation setTranslatesAutoresizingMaskIntoConstraints:NO];
NSDictionary *viewsDictionary = @{@"buttonAnimation":self.buttonAnimation};
[self.csArray addObjectsFromArray:[NSLayoutConstraint
constraintsWithVisualFormat:@"H:|-50-[buttonAnimation(100)]"
options:0
metrics:nil
views:viewsDictionary]];
[self.csArray addObjectsFromArray:[NSLayoutConstraint
constraintsWithVisualFormat:@"V:|-50-[buttonAnimation(100)]"
options:0
metrics:nil
views:viewsDictionary]];
[self.view addConstraints:self.csArray];
[self.buttonAnimation layoutIfNeeded];
} completion:^(BOOL finished) {
self.boolButtonAnimation = YES;
}];
} else {
[UIView transitionWithView:self.buttonAnimation
duration:1.0
options:UIViewAnimationOptionTransitionFlipFromTop
animations:^{
[self.buttonAnimation setTranslatesAutoresizingMaskIntoConstraints:NO];
NSDictionary *viewsDictionary = @{@"buttonAnimation":self.buttonAnimation};
[self.csArray addObjectsFromArray:[NSLayoutConstraint
constraintsWithVisualFormat:@"H:|-150-[buttonAnimation(100)]"
options:0
metrics:nil
views:viewsDictionary]];
[self.csArray addObjectsFromArray:[NSLayoutConstraint
constraintsWithVisualFormat:@"V:|-150-[buttonAnimation(100)]"
options:0
metrics:nil
views:viewsDictionary]];
[self.view addConstraints:self.csArray];
[self.buttonAnimation layoutIfNeeded];
} completion:^(BOOL finished) {
self.boolButtonAnimation = NO;
}];
}
}
@end