swift3.0_Constraints 的应用

本文介绍如何在iOS应用中为自定义视图设置Auto Layout约束,包括关闭autoresizing、设置中心点、宽度和高度的约束,并激活这些约束。

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

func setViewConstraints() {

        //系统默认会给autoresizing 约束,要关闭autoresizing才能让自定义的约束生效,否则程序崩溃

        customView.translatesAutoresizingMaskIntoConstraints = false

        //添加约束:"哪个控件" 什么属性“ "等于/大于/小于" “另一个控件什么属性乘以 "多少" 加上 "多少"

        let Constraint_centerX = NSLayoutConstraint(item: customView, attribute: .centerX, relatedBy: .equal, toItem: otherView, attribute: .centerX, multiplier: 1, constant: 0)

        

        let Constraint_centerY = NSLayoutConstraint(item: customView, attribute: .centerY, relatedBy: .equal, toItem: otherView, attribute: .centerY, multiplier: 1, constant: 0)

        

        let Constraint_width = NSLayoutConstraint(item: customView, attribute: .width, relatedBy: .lessThanOrEqual, toItem: otherView, attribute: .width, multiplier: 1, constant: 20)

        

        let Constraint_height = NSLayoutConstraint(item: customView, attribute: .height, relatedBy: .lessThanOrEqual, toItem: otherView, attribute: .height, multiplier: 1, constant: 20)


 //激活约束

      NSLayoutConstraint.activate([Constraint_centerX,Constraint_centerY,Constraint_width,Constraint_height])

    }


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值