So my UIViewController is embedded in a navigation controller. I programatically add the navigation buttons and now trying to add a scrollView below this navigation bar. The problem I'm having is this is filling the full frame size and going under the navigation bar.
How do I programatically set constraints of this scrollview?
var scrollView: UIScrollView!
var containerView = UIView()
override func viewDidLoad() {
super.viewDidLoad()
self.navigationItem.title = "Filters"
// add some buttons on the navigation
self.scrollView = UIScrollView()
self.scrollView.backgroundColor = UIColor.grayColor()
self.scrollView.contentSize = CGSizeMake(self.view.frame.size.width, self.view.frame.size.height)
containerView = UIView()
scrollView.addSubview(containerView)
view.addSubview(scrollView)
let label = UILabel(frame: CGRectMake(0, 0, 100, 21))
label.text = "my label"
containerView.addSubview(label)
}
Use the
contentInset
property of yourUIScrollView
. For example if you want a gap of 44 points at the top:While Clafou's answer is certainly correct, if you don't need transparency and want to start under navigation bar, the really proper way is to change behavior of the ViewController so it fits the content properly. To do that, you have two options:
1) Assuming you have Storyboard, go to ViewController Attributes Inspector and disable "Under top bars"
2) Assuming you are everything through code, you will want to look for following properties -
edgesForExtendedLayout
, andextendedLayoutIncludesOpaqueBars
. There is great answer for that already on SO so I won't cover it here.Hope it helps!
In Objective-C I usually set the 'edgesForExtendedLayout' Property to UIRectEdgeNone:
Nevertheless I would recommend to bind the Constraints to the topLayoutGuide
Hope this works for you.
The only way I managed to get this working on iOS11 was like this
While using
auto-layout
, just make sure that you give thetop-constraint
ofUIScrollView
withTop Layout Guide
, not withsuperview
of scroll view.