'Is it possible to pin a UIView's top to the bottom of the navigation bar?
I'm trying to position my UIView to be 20pt under the navigation bar, but when I set it relative to the view on the view controller it's still under the navigation bar at 20pt, and I don't want to hardcode it.
Is it possible to position it away from the navigation bar?
Solution 1:[1]
Try adding contraint with TopLayoutGuide,
The main difference between TopLayoutGuide and self.view is, top layout guide starts with bottom of status bar + bottom of navigation bar(if exist), but self.view always start from (0,0) coordinate in iOS 7 for translucent navigation bar.
So in your case you should try pinning from top layout guide.


Solution 2:[2]
To do this programmatically use the topLayoutGuide of your view controller:
override func viewDidLoad() {
...
myView.topAnchor.constraint(equalTo: self.topLayoutGuide.bottomAnchor).isActive=true
...
}
Solution 3:[3]
From iOS 11.0 programmatically you can use view.safeAreaLayoutGuide:
override func viewDidLoad() {
...
label.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor).isActive=true
}
Solution 4:[4]
Pin to the top safe area layout guide. Code if your are using SnapKit:
titleLabel.snp.makeConstraints { make in
make.top.equalTo(view.safeAreaLayoutGuide.snp.top).offset(20)
make.leading.equalToSuperview()
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Mohd Iftekhar Qurashi |
| Solution 2 | andrewz |
| Solution 3 | denis_lor |
| Solution 4 | Pavel Paddubotski |
