iOS 用XIB约束后,用代码修改约束

在iOS开发中,使用XIB和AutoLayout后,有时需要在代码中修改约束以适应不同机型或调整视图frame。可以将约束拖动到View或ViewController上,并通过属性引用进行修改。例如:`@property (weak, nonatomic) IBOutlet NSLayoutConstraint *topLayout;`,并且可以通过全局的机型适配单例来实现更便捷的修改。" 106508245,9676017,Android即时通讯(IM)客户端开发:基于XMPP的实战教程,"['Android开发', '即时通讯', 'XMPP协议', '客户端应用', '移动开发']

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

当使用xib,并使用了AutoLayout之后,当需要适配机型时,或者手动更改视图的frame的时候,就需要修改约束啦.其实很简单的.
1.首先从xib中吧改变的约束拖到view上或者ViewController上
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *topLayout;

机型封装到单例中 全局都可以使用

+ (UIScreenSizeType)currentScreenSizeType
{
    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重新添加一个约束
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值