iOS 11 - centering UIImageView in UIScrollView

I'm building a simple photo viewer, with a UIImageView inside a UIScrollView. This should allow zooming and scrolling. When it's zoomed out, the image should be centered in the scrollview.


I've done this before (and having working code), but want to try using the new UIScrollView.contentLayoutGuide property in iOS 11. According to the WWDC videos, this is supposed to simplify centering the view, along these lines:


imageview.centerXAnchor.constraint(equalTo: scrollview.contentLayoutGuide.centerXAnchor)
imageview.centerYAnchor.constraint(equalTo: scrollview.contentLayoutGuide.centerYAnchor)


However, everything I've tried has either failed to center the view (image zooms perfectly but moves to top left when zoomed out), or has centered it with wildly wrong zooming (image starts centered, but when zoomed in moves rapidly past the top left corner of the screen).


Has anyone got this to work, and if so how?

Replies

This is the solution you are / everybody is looking for. In my case I want to center a view inside a table view scroll view. So if the table view scrolls the custom view will always be in the center of the scroll view content.



// create a view
let v:UIView = UIView(frame:CGRect.zero)    // use zero if using constraints
    ibTableView.addSubview(v)
    ibTableView.bringSubview(toFront:v)
v.translatesAutoresizingMaskIntoConstraints = no
v.backgroundColor = .yellow
v.widthAnchor.constraint(equalToConstant:100).isActive = yes
v.heightAnchor.constraint(equalToConstant:100).isActive = yes

// set scrollview guides
ibTableView.contentLayoutGuide.widthAnchor.constraint(equalTo:ibTableView.frameLayoutGuide.widthAnchor).isActive = yes
ibTableView.contentLayoutGuide.heightAnchor.constraint(equalTo:ibTableView.frameLayoutGuide.heightAnchor).isActive = yes

// anchor view
v.centerXAnchor.constraint(equalTo:ibTableView.contentLayoutGuide.centerXAnchor).isActive = yes
v.centerYAnchor.constraint(equalTo:ibTableView.contentLayoutGuide.centerYAnchor).isActive = yes