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重新添加一个约束

你可能感兴趣的:(iOS 用XIB约束后,用代码修改约束)