使用系統自動布局方法-示例

[NSLayoutConstraint constraintsWithVisualFormat:<visual format string>options:<options>metrics:<metrics>views: <views dictionary>];

constraintsWithVisualFormat:參數為NSString型,指定Contsraint的屬性,是垂直方向的限定還是水平方向的限定,參數定義一般如下:

V:|-(>=XXX) :表示垂直方向上相對于SuperView大于、等于、小于某個距離

若是要定義水平方向,則將V:改成H:即可

在接著后面-[]中括號里面對當前的View/控件 的高度/寬度進行設定;

options:字典類型的值;這里的值一般在系統定義的一個enum里面選取

metrics:nil;一般為nil ,參數類型為NSDictionary,從外部傳入 //衡量標準

views:就是上面所加入到NSDictionary中的綁定的View

在這里要注意的是 AddConstraints 和 AddConstraint 之間的區別,一個添加的參數是NSArray,一個是NSLayoutConstraint

使用規則

|: 表示父視圖 

-:表示距離  

V:表示垂直  

H:表示水平

>= :表示視圖間距、寬度和高度必須大于或等于某個值    

<= :表示視圖間距、寬度和高度必須小宇或等于某個值    

== :表示視圖間距、寬度或者高度必須等于某個值

@  :>=、<=、==  限制   最大為  1000

1.|-[view]-|:  視圖處在父視圖的左右邊緣內

2.|-[view]  :   視圖處在父視圖的左邊緣

3.|[view]   :   視圖和父視圖左邊對齊

4.-[view]-  :  設置視圖的寬度高度

5.|-30.0-[view]-30.0-|:  表示離父視圖 左右間距  30

6.[view(200.0)] : 表示視圖寬度為 200.0

7.|-[view(view1)]-[view1]-| :表示視圖寬度一樣,并且在父視圖左右邊緣內

8. V:|-[view(50.0)] : 視圖高度為  50

9: V:|-(==padding)-[imageView]->=0-[button]-(==padding)-| : 表示離父視圖的距離為Padding,這兩個視圖間距必須大于或等于0并且距離底部父視圖為 padding

10:  [wideView(>=60@700)]  :視圖的寬度為至少為60 不能超過  700 ,最大為1000

蘋果官方示例代碼

- (void)viewDidLoad {
    UIScrollView *scrollView;
    UIImageView *imageView;
    NSDictionary *viewsDictionary;
 
    // Create the scroll view and the image view.
    scrollView  = [[UIScrollView alloc] init];
    imageView = [[UIImageView alloc] init];
 
    // Add an image to the image view.
    [imageView setImage:[UIImage imageNamed:"MyReallyBigImage"]];
 
    // Add the scroll view to our view.
    [self.view addSubview:scrollView];
 
    // Add the image view to the scroll view.
    [scrollView addSubview:imageView];
 
    // Set the translatesAutoresizingMaskIntoConstraints to NO so that the views autoresizing mask is not translated into auto layout constraints.
    scrollView.translatesAutoresizingMaskIntoConstraints  = NO;
    imageView.translatesAutoresizingMaskIntoConstraints = NO;
 
    // Set the constraints for the scroll view and the image view.
    viewsDictionary = NSDictionaryOfVariableBindings(scrollView, imageView);
    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[scrollView]|" options:0 metrics: 0 views:viewsDictionary]];
    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[scrollView]|" options:0 metrics: 0 views:viewsDictionary]];
    [scrollView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[imageView]|" options:0 metrics: 0 views:viewsDictionary]];
    [scrollView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[imageView]|" options:0 metrics: 0 views:viewsDictionary]];
 
    /* the rest of your code here... */
}
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容