使用AutoLayout 是否能实现A视图宽是B视图的3倍,B视图的宽是A视图的2倍

    //A视图的宽是B视图的3倍,B视图的宽是A视图的2倍
    UIView *viewA = [[UIView alloc]initWithFrame:CGRectMake(100, 20, 100, 100)];
    viewA.backgroundColor =[UIColor redColor];
    [self.view addSubview:viewA];
    viewA.translatesAutoresizingMaskIntoConstraints = NO;
    
    UIView *viewB = [[UIView alloc]initWithFrame:CGRectMake(100, 200, 100, 100)];
    viewB.backgroundColor = [UIColor blackColor];
    [self.view addSubview:viewB];
    viewB.translatesAutoresizingMaskIntoConstraints = NO;
    
    NSLayoutConstraint *constraint;
    constraint = [NSLayoutConstraint constraintWithItem:viewA attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:viewB attribute:NSLayoutAttributeWidth multiplier:3.0f constant:0.f];
    [self.view addConstraint:constraint];
    
    constraint = [NSLayoutConstraint constraintWithItem:viewB attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:viewA attribute:NSLayoutAttributeWidth multiplier:2.0f constant:0.f];
    [self.view addConstraint:constraint]; 
AutoLayout 还是很好玩的

你可能感兴趣的:(iOS基础)