Autolayout - UIView无法正确调整子视图的大小

问题描述:

我试图以编程方式创建一个UIViewUILabel作为子视图使用自动布局。Autolayout - UIView无法正确调整子视图的大小

约束

我用下面的约束上view

  • 的centerX的viewfastAttacksContainerView(上海华)

  • 顶部常数8对超视图的约束。

  • 然后创建的label其是恒定8 view并加入约束一个子视图,底部,和view

问题

view只调整大小以标签的和不占的恒定8上的所有4个侧面的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

+0

为什么你不使用的故事板? – Igor

+0

上面提到的代码将被迭代,因为'view'的数量在运行时被获取。 – an23lm

view具有不明确的高度。

你应该添加约束的高度view或距离它的底部fastAttacksContainerView

+0

不**视图**在**顶部**和+ **在**底部**上取得'label' + 8的高度? – an23lm

+0

尝试用'label.addConstraints([labLeft,labTop,labRigth,labBottom])替换'view.addConstraints([labLeft,labTop,labRigth,labBottom])'' – Igor

+0

程序崩溃了'View层次结构没有为约束“错误。 – an23lm

我设法使在故事板类似的设置,并在复制的约束来解决这个问题

的事情,我改变了:

  • 使用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)