Shark Deng

Interactive Designer @Shanju Design in Shanghai

touched caffe / mxnet / python / wordpress / bootstrap / Arduino / Raspberry Pi / webgl / three.js / PIXI / 3dMax

Email

Github

NSLayoutConstraint

2019-11-20 17:32:42

直接上码!

 let a = UIView(frame: CGRect(origin: .zero, size: CGSize(width: 200, height: 200)))
        self.view.addSubview(a)
        a.backgroundColor = UIColor.brown
        a.translatesAutoresizingMaskIntoConstraints = false //把自动调整关掉,不然会出错
        
        let width = NSLayoutConstraint(item: a, attribute: .width, relatedBy: .equal, toItem: self.view, attribute: .width, multiplier: 1.0, constant: 0.0)
        a.superview?.addConstraint(width)
        
        let height = NSLayoutConstraint(item: a, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 0.0, constant: 300)
        a.addConstraint(height)
        
        let centerX = NSLayoutConstraint(item: a, attribute: .centerX, relatedBy: .equal, toItem: self.view , attribute: .centerX, multiplier: 1.0, constant: 0.0)
        a.superview?.addConstraint(centerX)  //是superview,不然会报not in view tree错误
        
        let centerY =
        NSLayoutConstraint(item: a, attribute: .centerY, relatedBy: .equal, toItem: self.view , attribute: .centerY, multiplier: 1.0, constant: 0.0)
        a.superview?.addConstraint(centerY)

 



——By SharkDeng
如果你喜欢我的文章,欢迎红包赞赏

Leave a Reply

Your email address will not be published. Required fields are marked *