iOS AutoLayout 簡單運用(純程式碼)
阿新 • • 發佈:2019-01-25
舉例說明:建立一個grayView(寬150 高100 距上200 距左100)
方法一:原生API
UIView *grayView = [UIView new]; grayView.backgroundColor = [UIColor lightGrayColor]; // 禁止將 autoresizingmask 轉換為 constraints grayView.translatesAutoresizingMaskIntoConstraints = NO; [self.view addSubview:grayView]; // 新增 width 約束 NSLayoutConstraint *widthConstraint = [NSLayoutConstraint constraintWithItem:grayView attribute:(NSLayoutAttributeWidth) relatedBy:(NSLayoutRelationEqual) toItem:nil attribute:(NSLayoutAttributeNotAnAttribute) multiplier:0.0 constant:150]; // 新增 height 約束 NSLayoutConstraint *heightConstraint = [NSLayoutConstraint constraintWithItem:grayView attribute:(NSLayoutAttributeHeight) relatedBy:(NSLayoutRelationEqual) toItem:nil attribute:(NSLayoutAttributeNotAnAttribute) multiplier:0.0 constant:100]; // 新增 left 約束 NSLayoutConstraint *leftConstraint = [NSLayoutConstraint constraintWithItem:grayView attribute:(NSLayoutAttributeLeft) relatedBy:(NSLayoutRelationEqual) toItem:self.view attribute:(NSLayoutAttributeLeft) multiplier:1.0 constant:100]; // 新增 top 約束 NSLayoutConstraint *topConstraint = [NSLayoutConstraint constraintWithItem:grayView attribute:(NSLayoutAttributeTop) relatedBy:(NSLayoutRelationEqual) toItem:self.view attribute:(NSLayoutAttributeTop) multiplier:1.0 constant:200]; [grayView addConstraint:widthConstraint]; [grayView addConstraint:heightConstraint]; [self.view addConstraint:leftConstraint]; [self.view addConstraint:topConstraint];
方法二:VFL(Visual Format Language)
UIView *grayView = [UIView new]; grayView.backgroundColor = [UIColor lightGrayColor]; grayView.translatesAutoresizingMaskIntoConstraints = NO; [self.view addSubview:grayView]; // format引數 NSString *Hvfl = @"H:|-left-[grayView(150)]"; NSString *Vvfl = @"V:|-top-[grayView(100)]"; // 設定 margin 數值 NSDictionary *metrics = @{@"top":@200,@"left":@100}; // 把要新增約束的view 轉成字典 NSDictionary *views = NSDictionaryOfVariableBindings(grayView);// 這個方法會自動把傳入的引數椅子墊的形式返回,字典的key就是其本身的名字,如@{@"grayView":grayView} // 新增對齊方式 NSLayoutFormatOptions ops = NSLayoutFormatAlignAllLeft | NSLayoutFormatAlignAllTop;// 左邊與頂部 NSArray *Hconstraints = [NSLayoutConstraint constraintsWithVisualFormat:Hvfl options:ops metrics:metrics views:views]; NSArray *Vconstraints = [NSLayoutConstraint constraintsWithVisualFormat:Vvfl options:ops metrics:metrics views:views]; [self.view addConstraints:Hconstraints]; [self.view addConstraints:Vconstraints];
執行如下:
本篇部落格只是針對基礎知識點的整理歸納與簡單應用 詳細程式碼解析請參考如下部落格: