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



demo地址 :链接: http://pan.baidu.com/s/1c00ipDQ 密码: mi4c




1
@interface ViewController () 2 3 @property (nonatomic, strong) UILabel *label; 4 5 @end 6 7 @implementation ViewController 8 9 - (void)viewDidLoad { 10 [super viewDidLoad]; 11 12 //创建一个Label 13 UILabel *label = [[UILabel alloc] init]; 14 label.text = @"test"; 15 label.backgroundColor = [UIColor orangeColor]; 16 [self.view addSubview:label]; 17 self.label = label; 18 }
#pragma mark -- 在视图将要显示的时候 设置位置
- (void)viewWillAppear:(BOOL)animated {
    
     self.label.centerX -= self.view.width;
     self.label.centerY = 80;
}
#pragma mark --在视图现实的时候
- (void)viewDidAppear:(BOOL)animated {
    
    /*当一个自定义view的某个属性发生改变,
     并且可能影响到constraint时,
     需要调用此方法去标记constraints需要在未来的某个点更新,
     系统然后调用updateConstraints.
     */
    [self.view setNeedsUpdateConstraints];
    
    //设置动画
    [UIView animateWithDuration:1 animations:^{
        
        //关闭系统的自动布局
        self.label.translatesAutoresizingMaskIntoConstraints = NO;
        
        //将自己的属性存放到数组中
        NSDictionary *dict = @{@"label": self.label};
        
        //设定约束
        //设置水平约束条件
        NSArray *arrayH = [NSLayoutConstraint constraintsWithVisualFormat:@"H:|-80-[label]-80-|" options:0 metrics:nil views:dict];
        //设置垂直约束条件
        NSArray *arrayV = [NSLayoutConstraint constraintsWithVisualFormat:@"V:|-80-[label]" options:0 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];  

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

 

posted on 2015-08-22 15:35  Hwangkop  阅读(332)  评论(1编辑  收藏  举报

导航