iOS代码布局适配(系统的方法两种)

1.Layout:代码布局

UIView *viewA = [[UIView alloc]init];

    viewA.backgroundColor = [UIColor redColor];

    viewA.translatesAutoresizingMaskIntoConstraints = NO;

    [self.view addSubview:viewA];

11距离相对视图上面的距离

    NSLayoutConstraint *aTop = [NSLayoutConstraint constraintWithItem:viewA attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeTop multiplier:1 constant:200];

1-2距离父视图左边的距离

    NSLayoutConstraint *aLeft = [NSLayoutConstraint constraintWithItem:viewA attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeLeft multiplier:1 constant:100];

1-3视图本身的宽

    NSLayoutConstraint *aWidth = [NSLayoutConstraint constraintWithItem:viewA attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:0 constant:50];

1-4视图本身的高

    NSLayoutConstraint *aHeight = [NSLayoutConstraint constraintWithItem:viewA attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:0 constant:50];

    [self.view addConstraints:@[aTop,aLeft,aWidth,aHeight]];



2.另外一种可视化视图的代码布局:代码量比较少

 UIView *viewA = [[UIView alloc]init];

    viewA.backgroundColor = [UIColor redColor];

    viewA.translatesAutoresizingMaskIntoConstraints = NO;

    [self.view addSubview:viewA];

CGFloat offsetX = 50;

    2-1NSArray *viewACons = [NSLayoutConstraint constraintsWithVisualFormat:@"H:[viewA(width)]-10-|" options:0 metrics:@{@"width":[NSNumber numberWithFloat:offsetX]} views:NSDictionaryOfVariableBindings(viewA)];

     [self.view addConstraints:viewACons];

   2-2 NSArray *viewAConsH = [NSLayoutConstraint constraintsWithVisualFormat:@"V:|-200-[viewA(==50)]" options:0 metrics:nil views:NSDictionaryOfVariableBindings(viewA)];

    [self.view addConstraints:viewAConsH];

你可能感兴趣的:(布局,代码布局)