2016-02-29 53 views
3

我试图约束添加到导航栏,我有UIImageView,其中有宽度,高度和水平居中,我想UIImagenavigationBar之间的垂直空间为0,我尝试这种像1小时,无法弄清楚如何,我尝试添加约束UIView,并添加常数navbarHeight + statusBarHeight,和它的工作,但我想使imageview的关系和导航栏添加约束到的导航栏编程方式斯威夫特

let verticalSpace = NSLayoutConstraint(item: image, attribute: .Top, relatedBy: .Equal, toItem: self.view, attribute: .Top, multiplier: 1, constant: 0) 
view.addConstraint(verticalSpace) // this works 

回答

4

尝试topLayoutGuide

let verticalSpace = NSLayoutConstraint(item: image, 
             attribute: .Top, 
             relatedBy: .Equal, 
             toItem: self.topLayoutGuide, 
             attribute: .Bottom, 
             multiplier: 1, constant: 0) 

上述约束的解释:

只是其名为:image.Top之间垂直空间& self.topLayoutGuide.Bottom = 0

这意味着附着有底部imageview的顶约束topLayoutGuide的属性为常数0.

+1

是的,这有效,但请你解释这两个“属性”之间的差异,有人说。顶部说.Bottom,为什么? – nikagar4

+0

是的,我明白了一切,现在感谢你:) – nikagar4

+0

我刚才意识到这不工作时,使用outlet UIImageView,你能告诉我为什么吗? – nikagar4

1

带锚点:

image.topAnchor.constraint(equalTo: topLayoutGuide.bottomAnchor).isActive = true