【问题标题】:Setting Autolayout programatically in swift not working以编程方式快速设置自动布局不起作用
【发布时间】:2015-04-08 12:59:36
【问题描述】:

我在我的 storyBoardViewController 中添加了一个 sampleuiview(200,200),并将它的出口与 viewcontroller 连接起来。

现在我想添加一些约束假设 (Top - 200,Leading-100, Trailing -100) 和一些宽度、高度和中心位置

我写了一段代码:

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 文件中添加的子视图

【问题讨论】:

  • 你打电话给 [controller.view setNeedsDisplay] 了吗?
  • 这段代码是在什么方法中调用的?
  • 我在view中添加了会出现[我需要在哪里设置needsdisplay?]
  • “但它不起作用” that 是什么意思?
  • 表示我设置的任何常数值,框视图保持在一个静态位置。它的位置没有改变

标签: swift autolayout nslayoutconstraint


【解决方案1】:

self.view是viewcontroller的子视图,self.view不能有任何约束。 boxView 可以有约束,因此它的位置和大小可以相对于作为其父视图的self.view

viewWillAppear 中添加约束即可,不需要setNeedsDisplay

您是否要在视图控制器中定位 boxView

【讨论】:

  • 我在 Storyboard xib 文件中添加了 boxView。(使用拖放)。并连接它的出口连接,然后以编程方式设置它的约束,我只想看看如何以这种方式设置自动布局,这样我就可以用更多的动画来玩它
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-12-26
相关资源
最近更新 更多