视图的底部和右侧约束是否定的?

问题描述:

这是一种将子视图固定到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增添几分的填充物,右侧和底部约束走另一条路!因此,而不是子视图比超级视图小16磅的大16pts?顶部和左侧按预期行事。

请注意,如果我将顶部和左侧设置为16,但底部和右侧到-16这会产生所需的结果,但我不应该这样做?我哪里错了?

很多谢谢。

约束中的项目顺序很重要。

变化

let bottom = NSLayoutConstraint(item: view, attribute: .bottom, relatedBy: .equal, toItem: base, attribute: .bottom, multiplier: 1, constant: 0) 
let right = NSLayoutConstraint(item: view, attribute: .right, relatedBy: .equal, toItem: base, attribute: .right, multiplier: 1, constant: 0) 

let bottom = NSLayoutConstraint(item: base, attribute: .bottom, relatedBy: .equal, toItem: view, attribute: .bottom, multiplier: 1, constant: 0) 
let right = NSLayoutConstraint(item: base, attribute: .right, relatedBy: .equal, toItem: view, attribute: .right, multiplier: 1, constant: 0) 

尝试这样的想法:把第二个项目为原点。如果该值为正,则第一项是第二项的右侧/底部方向。如果该值为负数,则表示方向是左侧,顶部是第二个项目。

既然你想放viewbase里面,要在约束正值,则需要使用base的第一个项目,view在约束第二项(起源)。所以这意味着当约束常数为正时,base位于右侧/底部至view

+0

现在完全合乎逻辑,我以这种方式思考它,谢谢你的一个坚实的解释和例子。 :) –

+0

欢迎:) – Elvin

听起来很疯狂。它可以不看,但现在我倾向于设置限制了在故事板,为他们创造网点和改变他们喜欢:

self.menuTopConstraint.constant = 64 

会向下移动菜单的顶部约束到导航栏的底部酒吧。

通过菜单的高度,是我的主要观点滑下:

self.mainViewBottomConstraint.constant = self.indexHeight * -1 

欣赏它没有解决的问题头上。当我有更多时间时可以看。