NSLayoutConstraint 布局,配合简单的动画效果

时间:2023-03-10 06:49:47
NSLayoutConstraint 布局,配合简单的动画效果


demo地址 :链接: http://pan.baidu.com/s/1c00ipDQ 密码: mi4c
1 @interface ViewController () @property (nonatomic, strong) UILabel *label; @end @implementation ViewController - (void)viewDidLoad {
[super viewDidLoad]; //创建一个Label
UILabel *label = [[UILabel alloc] init];
label.text = @"test";
label.backgroundColor = [UIColor orangeColor];
[self.view addSubview:label];
self.label = label;
}
#pragma mark -- 在视图将要显示的时候 设置位置
- (void)viewWillAppear:(BOOL)animated { self.label.centerX -= self.view.width;
self.label.centerY = ;
}
#pragma mark --在视图现实的时候
- (void)viewDidAppear:(BOOL)animated { /*当一个自定义view的某个属性发生改变,
并且可能影响到constraint时,
需要调用此方法去标记constraints需要在未来的某个点更新,
系统然后调用updateConstraints.
*/
[self.view setNeedsUpdateConstraints]; //设置动画
[UIView animateWithDuration: animations:^{ //关闭系统的自动布局
self.label.translatesAutoresizingMaskIntoConstraints = NO; //将自己的属性存放到数组中
NSDictionary *dict = @{@"label": self.label}; //设定约束
//设置水平约束条件
NSArray *arrayH = [NSLayoutConstraint constraintsWithVisualFormat:@"H:|-80-[label]-80-|" options: metrics:nil views:dict];
//设置垂直约束条件
NSArray *arrayV = [NSLayoutConstraint constraintsWithVisualFormat:@"V:|-80-[label]" options: metrics:nil views:dict];
//添加约束
[self.view addConstraints:arrayH];
[self.view addConstraints:arrayV]; // 当视图发生改变的时候layoutIfNeeded 方法来强制进行布局
[self.label layoutIfNeeded]; } completion:nil];
}

可以将约束变成自己的一个属性,每次要改变约束的时候,删除相关的约束 例如:

@property (nonatomic, copy) NSArray *arrayV;
self.arrayV = [NSLayoutConstraint constraintsWithVisualFormat:@"V:|-80-[label]" options:0 metrics:nil views:dict];
当要改变约束的时候,将它移除:

[self.view removeConstraint:self.arrayV];  

虽然这样做有点前期麻烦,但是做成之后就觉得非常值得了