iOS 用XIB約束后,用代碼修改約束

當使用xib,并使用了AutoLayout之后,當需要適配機型時,或者手動更改視圖的frame的時候,就需要修改約束啦.其實很簡單的.
1.首先從xib中吧改變的約束拖到view上或者ViewController上

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *topLayout;

//機型封裝到單例中 全局都可以使用

    if (CGSizeEqualToSize(CGSizeMake(640, 960), [[UIScreen mainScreen] currentMode].size)) {
        return UIScreenSizeType_640x960;
    }
    else if(CGSizeEqualToSize(CGSizeMake(640, 1136), [[UIScreen mainScreen] currentMode].size)){
        return UIScreenSizeType_640x1136;
    }else if(CGSizeEqualToSize(CGSizeMake(750, 1334), [[UIScreen mainScreen] currentMode].size)){
        return UIScreenSizeType_750x1334;
    }else if(CGSizeEqualToSize(CGSizeMake(1242, 2208), [[UIScreen mainScreen] currentMode].size)){
        return UIScreenSizeType_1242x2208;
    }
    return UIScreenSizeType_000x000;}

        if([UIScreen currentScreenSizeType] == UIScreenSizeType_640x960){
            _topLayout.constant = 40;
        }else if([UIScreen currentScreenSizeType] == UIScreenSizeType_640x1136){
            _topLayout.constant = 40;
        }else if([UIScreen currentScreenSizeType] == UIScreenSizeType_750x1334){
            _topLayout.constant = 40;
        }else if([UIScreen currentScreenSizeType] == UIScreenSizeType_1242x2208){
            _topLayout.constant = 40;
        }

2.還可以為控件自定義一個約束

  NSLayoutConstraint *myConstraint =[NSLayoutConstraint
                        constraintWithItem:iSinaButton //子試圖
                        attribute:NSLayoutAttributeCenterX //子試圖的約束屬性
                        relatedBy:NSLayoutRelationEqual //屬性間的關系
                        toItem:self.view//相對于父試圖
                         attribute:NSLayoutAttributeCenterX//父試圖的約束屬性
                         multiplier:1.0 
                         constant:0.0];// 固定距離
[self.view addConstraint: myConstraint];//為iSinaButton重新添加一個約束
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容