我在storyBoardViewController中添加了一个sampleuiview(200,200)并使用viewcontroller连接了它的插座。
现在我想添加一些约束(Top - 200,Leading-100,Trailing -100)和一些widhth,height和Center Position
我写了一个代码:
boxView.setTranslatesAutoresizingMaskIntoConstraints(false)
let leading = NSLayoutConstraint(item: boxView, attribute: .Leading, relatedBy: .Equal, toItem: self.view, attribute: .Leading, multiplier: 1.0, constant: 60)
self.view.addConstraint(leading)
let widthC = NSLayoutConstraint(item: boxView, attribute: .Width, relatedBy: .Equal, toItem: self.view, attribute: .Width, multiplier: 0.5, constant: 60)
self.view.addConstraint(widthC)
let heightC = NSLayoutConstraint(item: boxView, attribute: .Height, relatedBy: .Equal, toItem: self.view, attribute: .Height, multiplier: 0.5, constant: 0)
self.view.addConstraint(heightC)
let centerX = NSLayoutConstraint(item: boxView, attribute: .CenterX, relatedBy: .Equal, toItem: self.view, attribute: .CenterX, multiplier: 1.0, constant: 150)
self.view.addConstraint(centerX)
let centerY = NSLayoutConstraint(item: boxView, attribute: .CenterY, relatedBy: .Equal, toItem: self.view, attribute: .CenterY, multiplier: 1.0, constant: 0)
self.view.addConstraint(centerY)
但它不起作用。有什么问题吗?
P.S boxView是我在xib文件中添加的子视图
答案 0 :(得分:0)
self.view
是viewcontroller的子视图,self.view不能有任何约束。 boxView
可以有约束,以便它的位置和大小可以相对于self.view
,这是它的超级视图。
可以在viewWillAppear
中添加约束,而不需要setNeedsDisplay
。
您是否尝试将boxView
置于视图控制器中?