【发布时间】:2017-03-24 09:37:20
【问题描述】:
这是我将子视图固定到UIView 实例的方法。抱歉代码乱七八糟,我一直在尝试让它工作。
open static func withEmbeddedView(_ view: UIView, andFixedHeight height: CGFloat) -> PMGAlertControllerEmbedComponent {
let base = PMGAlertControllerEmbedComponent(frame: CGRect.zero)
base.addSubview(view)
view.translatesAutoresizingMaskIntoConstraints = false
base.translatesAutoresizingMaskIntoConstraints = false
let left = NSLayoutConstraint(item: view, attribute: .left, relatedBy: .equal, toItem: base, attribute: .left, multiplier: 1, constant: 0)
let right = NSLayoutConstraint(item: view, attribute: .right, relatedBy: .equal, toItem: base, attribute: .right, multiplier: 1, constant: 0)
let top = NSLayoutConstraint(item: view, attribute: .top, relatedBy: .equal, toItem: base, attribute: .top, multiplier: 1, constant: 0)
let bottom = NSLayoutConstraint(item: view, attribute: .bottom, relatedBy: .equal, toItem: base, attribute: .bottom, multiplier: 1, constant: 0)
base.addConstraints([left, right, top, bottom])
view.addConstraint(NSLayoutConstraint(item: view, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: height))
base.leftConstraint = left
base.rightConstraint = right
base.topConstraint = top
base.bottomConstraint = bottom
base.layoutIfNeeded()
return base
}
现在这本身可以正常工作,但是一旦我尝试在其他地方修改这些约束的常量,比如将它们设置为 16 以添加一些填充,右侧和底部约束就会相反!所以不是子视图比父视图小 16pts,而是比父视图大 16pts?顶部和左侧的行为符合预期。
请注意,如果我将顶部和左侧设置为 16,但底部和右侧设置为 -16,这会产生所需的结果,但我不应该这样做吗?我哪里错了?
非常感谢。
【问题讨论】:
标签: ios swift uiview nslayoutconstraint