Autolayout - UIView未正确调整大小以适应子视图的大小

时间:2016-08-13 22:20:01

标签: ios swift uiview autolayout uilabel

我尝试使用自动布局以编程方式创建UIView UILabel作为子视图。

约束

我在view上使用了以下约束:

  • CenterX viewfastAttacksContainerView (superview)

  • 顶级约束常量8到superview。

  • 然后创建了一个label,它是view的子视图,并为顶部底部添加了常量8的约束,< strong>左,view

问题

view仅调整标签的框架,并不考虑所有4边的常数8的4个约束。这导致label部分显示在view之外。

let view = UIView()
view.backgroundColor = pokemon.secondaryColor

let label = UILabel()

fastAttacksContainerView.addSubview(view)
view.translatesAutoresizingMaskIntoConstraints = false

view.addSubview(label)
label.translatesAutoresizingMaskIntoConstraints = false

label.text = fa

let gest = UITapGestureRecognizer(target: self, action: #selector(self.selectFastAttack))
view.addGestureRecognizer(gest)

fastAttackButtons.append(view)
fastAttackLables.append(label)

let top = NSLayoutConstraint(item: view, attribute: .Top, relatedBy: .Equal, toItem: fastAttacksContainerView, attribute: .Top, multiplier: 1, constant: 8)
let centerX = NSLayoutConstraint(item: view, attribute: .CenterX, relatedBy: .Equal, toItem: fastAttacksContainerView, attribute: .CenterX, multiplier: 1, constant: 0)

let labLeft = NSLayoutConstraint(item: label, attribute: .Left, relatedBy: .Equal, toItem: view, attribute: .Left, multiplier: 1, constant: 8)
let labTop = NSLayoutConstraint(item: label, attribute: .Top, relatedBy: .Equal, toItem: view, attribute: .Top, multiplier: 1, constant: 8)
let labRigth = NSLayoutConstraint(item: label, attribute: .Right, relatedBy: .Equal, toItem: view, attribute: .Right, multiplier: 1, constant: 8)
let labBottom = NSLayoutConstraint(item: label, attribute: .Bottom, relatedBy: .Equal, toItem: view, attribute: .Bottom, multiplier: 1, constant: 8)
view.addConstraints([labLeft, labTop, labRigth, labBottom])
fastAttacksContainerView.addConstraints([top, centerX])

输出

Simulation

2 个答案:

答案 0 :(得分:0)

view高度不明确。

您应该为view的高度或距离fastAttacksContainerView的底部添加约束。

答案 1 :(得分:0)

我设法通过在故事板上进行类似的设置并复制约束来解决这个问题。

我改变的事情:

  • 使用LeadingTrailing代替LeftRight布局属性。
  • 对于labLeftlabRight限制,我互换了itemtoItem。 (这对我来说似乎是一个错误。有人可以验证吗?)

代码更改:

let labLeft = NSLayoutConstraint(item: label, attribute: .Leading, relatedBy: .Equal, toItem: view, attribute: .Leading, multiplier: 1, constant: 8)
let labTop = NSLayoutConstraint(item: label, attribute: .Top, relatedBy: .Equal, toItem: view, attribute: .Top, multiplier: 1, constant: 8)
let labRigth = NSLayoutConstraint(item: view, attribute: .Trailing, relatedBy: .Equal, toItem: label, attribute: .Trailing, multiplier: 1, constant: 8)
let labBottom = NSLayoutConstraint(item: view, attribute: .Bottom, relatedBy: .Equal, toItem: label, attribute: .Bottom, multiplier: 1, constant: 8)