Clicky

iOS Dev Nugget 290 Auto Layout with UIScrollView

.

Need to run a code review on your codebase? Hire me

Using Auto Layout with UIScrollView is surprisingly simple. You just need to add constraints to the content that will fill the entire scrollview by anchoring to the 4 edges of the scroll view. You don't need to set the content size of the scroll view explicitly. This is because the 4 edges actually refer to the scroll view's content view rather than the scroll view itself.

let scrollView = UIScrollView()
content.translatesAutoresizingMaskIntoConstraints = false

let content = UIView()
//TODO: Set up `content`, adding subviews, etc
content.translatesAutoresizingMaskIntoConstraints = false
scrollView.addSubview(content)

NSLayoutConstraint.activate([
    content.leadingAnchor.constraint(equalTo: scrollView.leadingAnchor),
    content.trailingAnchor.constraint(equalTo: scrollView.trailingAnchor),
    content.topAnchor.constraint(equalTo: scrollView.topAnchor),
    content.bottomAnchor.constraint(equalTo: scrollView.bottomAnchor),

    //Of course you'll want to layout the scrollview itself. Likely occupying the entire parent
    scrollView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
    scrollView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
    scrollView.topAnchor.constraint(equalTo: view.topAnchor),
    scrollView.bottomAnchor.constraint(equalTo: footerBar.topAnchor),

    //TODO set up constraints for `content` as you would have if there was no `UIScrollView` involved
])

Your feedback is valuable: Do you want more nuggets like this?   Yes   or   No

.

.

Like this and want such iOS dev nuggets to be emailed to you, weekly?

Sign Me Up! or follow @iosdevnuggets on Twitter

.

View archives of past issues