Autolayout - UIView无法正确调整子视图的大小
问题描述:
我试图以编程方式创建一个UIView
与UILabel
作为子视图使用自动布局。Autolayout - UIView无法正确调整子视图的大小
约束
我用下面的约束上view
:
的centerX的
view
到fastAttacksContainerView
(上海华)。顶部常数8对超视图的约束。
然后创建的
label
其是恒定8view
并加入约束顶一个子视图,底部,左,和右到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])
输出
答
我设法使在故事板类似的设置,并在复制的约束来解决这个问题
的事情,我改变了:
- 使用
Leading
和Trailing
,而不是Left
和Right
布局属性。 - 对于
labLeft
和labRight
约束,我互换item
和toItem
。 (这对我来说似乎是一个错误,任何人都可以验证吗?)
代码变化:
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)
为什么你不使用的故事板? – Igor
上面提到的代码将被迭代,因为'view'的数量在运行时被获取。 – an23lm