 代码布局(无snapkit应急用)

let labels = UILabel()
labels.backgroundColor = UIColor.blackColor()
labels.textColor = UIColor.whiteColor()
labels.layer.masksToBounds = true
labels.layer.cornerRadius = 5
labels.textAlignment = NSTextAlignment.Center
labels.alpha = 0.5
labels.text = "..."
super.view.addSubview(labels)

        //自动布局
        labels.translatesAutoresizingMaskIntoConstraints = false
        
        //底部约束
        let bottom:NSLayoutConstraint = NSLayoutConstraint(item: labels, attribute: NSLayoutAttribute.Bottom, relatedBy:NSLayoutRelation.Equal, toItem:self.view, attribute:NSLayoutAttribute.Bottom, multiplier:1.0, constant: -30)
        labels.superview!.addConstraint(bottom)//父控件添加约束
        
        //中心对齐
        let center:NSLayoutConstraint = NSLayoutConstraint(item: labels, attribute: NSLayoutAttribute.CenterX, relatedBy:NSLayoutRelation.Equal, toItem:self.view, attribute:NSLayoutAttribute.CenterX, multiplier:1.0, constant: 0)
        labels.superview!.addConstraint(center)//父控件添加约束
        
        //宽度约束
        let width:NSLayoutConstraint = NSLayoutConstraint(item: labels, attribute: NSLayoutAttribute.Width, relatedBy:NSLayoutRelation.Equal, toItem:nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier:0.0, constant:120)
        labels.addConstraint(width)//自己添加约束
      
        //高度约束
        let height:NSLayoutConstraint = NSLayoutConstraint(item: labels, attribute: NSLayoutAttribute.Height, relatedBy:NSLayoutRelation.Equal, toItem:nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier:0.0, constant:30)
        labels.addConstraint(height)//自己添加约束

你可能感兴趣的:( 代码布局(无snapkit应急用))