NSLayoutConstraint参数说明:
/**
* 创建约束 NSLayoutConstraint 参数 说明:
* item 自己
* attribute
* relatedBy 大于等于 小于等于 等于 ...
* toItem 另外一个控件
* attribute 另一个控件的属性
* multiplier 乘以多少
* constant : 加上多少
* NSLayoutConstraint : 某个控件的属性值 等于 另外一个控件的属性值
乘以多少 加上多少
* 添加约束 addConstraint
*/
NSLayoutConstraint(item: AnyObject, attribute: NSLayoutAttribute, relatedBy: NSLayoutRelation, toItem: AnyObject?, attribute: NSLayoutAttribute, multiplier: CGFloat, constant: CGFloat)
创建子控件
let childView = UILabel()
childView.text = "正在链接服务器"
childView.backgroundColor = UIColor.yellow //背影黄色
childView.textAlignment = .center //文本居中对齐
parentView.backgroundColor = UIColor.red//设置父元素背影红色,方便查看效果
关闭autoresizing
创建约束:
例:
Swift2.3
let imgCoupon = UIImageView()
imgCoupon.frame = CGRectMake(0, 0, 16, 16)
imgCoupon.loadImgByNamed("coupon")
imgCoupon.tag = 12345
cell.addSubview(imgCoupon)
imgCoupon.translatesAutoresizingMaskIntoConstraints = false
let l = NSLayoutConstraint(item: imgCoupon, attribute: .Leading, relatedBy: .Equal,
toItem: firstView, attribute: .Trailing, multiplier: 1, constant: 3)
l.active = true
let c = NSLayoutConstraint(item: imgCoupon, attribute: .CenterY, relatedBy: .Equal,
toItem: lbName, attribute: .CenterY, multiplier: 1, constant: 0)
c.active = true
let h = NSLayoutConstraint(item: imgCoupon, attribute: .Height, relatedBy: .Equal,
toItem: nil, attribute: .NotAnAttribute, multiplier: 1, constant: 16)
h.active = true
let w = NSLayoutConstraint(item: imgCoupon, attribute: .Width, relatedBy: .Equal,
toItem: nil, attribute: .NotAnAttribute, multiplier: 1, constant: 16)
w.active = true
Swfit2.3中使用w.active = true
而Swift3.0中是addConstraint(w),并且attribute的值也不同
请发表评论