5

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?

Doug Smith
  • 29,668
  • 57
  • 204
  • 388

5 Answers5

6

To do this programmatically use the topLayoutGuide of your view controller:

override func viewDidLoad() {
    ...
    myView.topAnchor.constraint(equalTo: self.topLayoutGuide.bottomAnchor).isActive=true
    ...
}
andrewz
  • 4,729
  • 5
  • 49
  • 67
4

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.

Top Layout Guide self.view

Mohd Iftekhar Qurashi
  • 2,385
  • 3
  • 32
  • 44
  • 1
    How would you do that programmatically? – Doug Smith Nov 10 '14 at 18:20
  • UIViewController has provide category properties to access topLayoutGuide and bottomLayoutGuide interface UIViewController (UILayoutSupport) // These objects may be used as layout items in the NSLayoutConstraint API property(nonatomic,readonly,retain) id topLayoutGuide NS_AVAILABLE_IOS(7_0); property(nonatomic,readonly,retain) id bottomLayoutGuide NS_AVAILABLE_IOS(7_0); end Take a look at this answer: http://stackoverflow.com/a/19779200/1582217 – Mohd Iftekhar Qurashi Nov 11 '14 at 07:03
2

From iOS 11.0 programmatically you can use view.safeAreaLayoutGuide:

override func viewDidLoad() {
    ...
    label.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor).isActive=true
}
denis_lor
  • 6,212
  • 4
  • 31
  • 55
0

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()
}
-5

So your UIView sits within a UIViewController, correct?

When you define your initial inner UIView to that UIViewController, can you set its coordinates to be 20px off the top of the ViewController?

For example:

//
//  ViewControllerEx.swift
//

import UIKit

class ViewControllerExample: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        var innerContainer = UIView(frame: CGRectMake(0, 20, self.view.bounds.width, self.view.bounds.height-20))

        self.view.addSubview(innerContainer)
    }  
}
Alex
  • 5,298
  • 4
  • 29
  • 34