Programmatic UIView Positioning With Rotation

Posted by Grego on January 8, 2017

In a previous post titled, So Long, Storyboards!, I mentioned how to size and position views programmatically. However, what I didn’t realize at the time was that screen rotation failed miserably. The code samples I supplied positioned the views relative to each other but the coordinates remained the same during rotation, turning this:

iOS sample app in portrait view

Into this:

iOS sample app in landscape view with bad positioning

Which, after some kajiggering, I managed to transform into this:

iOS sample app in landscape view with proper positioning

So, how do we get started?

The first thing you’ll notice right away is that one of the views is missing in landscape mode. This was a decision I made based on the fact that it didn’t really fit properly in landscape mode anymore and I didn’t know what else to do with it. This also served as an example of one thing to do when the views are dynamic and there isn’t enough space on the screen: hide unnecessary elements.

A few choices I can think of off the top of my head would be:

  • Throw everything into a scroll view and kept the positioning more or less the same.
  • Resize the views to make them fit better / collapse views if possible
  • Hide/show views based on whether or not they are necessary in that view.
  • Disallow rotation all together. This way if they turn the device nothing happens.

The decision of what to do mainly depends on the situation and in my case they were just a bunch of boxes that served no purpose. In a real app, you’d probably want to spend more time to think about what you might want to do in that situation.

Implementation

The trick to implementing this lies in a couple of methods:

These methods are fired when the screen changes size. From the Apple UIViewController docs - Handling View Rotations:

When a rotation occurs for a visible view controller, the willRotate(to:duration:), willAnimateRotation(to:duration:), and didRotate(from:) methods are called during the rotation. The viewWillLayoutSubviews() method is also called after the view is resized and positioned by its parent. If a view controller is not visible when an orientation change occurs, then the rotation methods are never called. However, the viewWillLayoutSubviews() method is called when the view becomes visible. Your implementation of this method can call the statusBarOrientation method to determine the device orientation.

My decision to implement viewWillLayoutSubview() was based on some sample Google iOS code that implemented layoutSubviews() in the UIView context.

I actually kept a lot of the sizing for the views in their closures:

lazy var cantTouchThisButton: UIButton! = {
  let button = UIButton(type: .system)
  button.setTitle("Can't touch this!!", for: .normal)
  button.sizeToFit()

  button.addTarget(self, action: #selector(cantTouchThisButton_tapped),
                   for: .touchUpInside)

  return button
}()

lazy var instructionsLabel: UILabel! = {
  let label = UILabel(frame: .zero)
  label.text = "To use this app, please check the link in the other thingamabob"
  label.numberOfLines = 0
  label.textAlignment = .center

  // set width to 75% of current view's width
  let width = self.view!.bounds.size.width * 0.75
  let size = label.sizeThatFits(CGSize(width: width, height: CGFloat.greatestFiniteMagnitude))

  var frame = label.frame
  frame.size = size
  label.frame = frame

  return label
}()

lazy var framedLabel: UILabel! = {
  let label = UILabel(frame: CGRect(x: 50, y: 70, width: 100, height: 100))

  label.backgroundColor = .gray

  return label
}()

but I removed all of the positioning code.

Now since I haven’t done much of this yet I’m still not sure how I feel about splitting up the code. It’s very possible that when rotating the sizes of the views would be expected to change as well.

I’d say it even makes sense to just initialize everything with the best designated initializers available i.e., init(frame:) for most views, then pass it .zero. Then set up all the event handlers, addTarget(), UIGestureRecognizers, etc. inside the closures. Maybe even do sizeToFit() if it makes sense. But for anything that will change size dynamically, do that and the positioning both in your viewWillLayoutSubviews() life cycle method, which in my example now looks like this:

/**
 * Repositions views accordingly, without using constraints
 */
override func viewWillLayoutSubviews() {
  // point positioned label is static from the top,
  // if it wasn't I couldn't call it a point positioned view anymore :|
  self.pointPositionedLabel.frame.origin = CGPoint(x: 160, y: 70)

  // the framed label is basically tied to the nav bar
  // with a set x coordinate.
  self.framedLabel.frame.origin = CGPoint(x: 50,
      y: self.navigationController!.navigationBar.frame.maxY + 6)

  if UIDevice.current.orientation == .portrait {
    // the center positioned label goes below the framedLabel
    // if we're in landscape, that obfuscates the instructions label
    // and can't touch this button so don't show it
    self.centerPositionedLabel.isHidden = false
    self.centerPositionedLabel.frame.origin = CGPoint(
        x: self.view.frame.midX - (self.centerPositionedLabel.frame.width / 2),
        y: self.framedLabel.frame.maxY + k.VIEW_MARGIN)
  }
  else {
    self.centerPositionedLabel.isHidden = true
  }

  // instructions label is center aligned
  self.instructionsLabel.center = self.view.center

  // can't touch this button goes below the instructions label.
  self.cantTouchThisButton.frame.origin = CGPoint(
      x: self.view.frame.midX - (self.cantTouchThisButton.frame.width / 2),
      y: self.instructionsLabel.frame.maxY + k.VIEW_MARGIN)

}

Adding a Pinch of Syntactic Sugar

The code above works, however it could be cleaner. The more DRY way of handling this would be to create some category methods.

I’ve created a small few for demonstration purposes:

//
//  View+Position.swift
//
//  A limited example of how to simplify programmatic view placement and sizing
//
//  NOTE: I HAVE NOT THOROUGHLY TESTED THIS CODE. IT MAY PRODUCE BUGS. USE AT
//        YOUR OWN RISK
//
//  NoStoryboard
//
//  Created by Gregory McQuillan on 1/7/17.
//  Copyright © 2017 One Big Function. All rights reserved.
//

import UIKit

extension UIView {
  /**
   * Places this view directly below `topView`
   */
  @discardableResult func placeBelow(_ topView: UIView,
                                     withMargin optMargin: CGFloat? = nil,
                                     x optX: CGFloat? = nil) -> UIView {
    let x = optX ?? self.frame.origin.x
    let y = topView.frame.maxY + (optMargin ?? 0)


    self.frame.origin = CGPoint(x: x, y: y)

    return self
  }

  func placeBelow(_ topView: UIView,
                  centeredTo centerToView: UIView,
                  withMargin optMargin: CGFloat? = nil) {
    let x = centerToView.frame.midX - (self.frame.width / 2)
    let y = topView.frame.maxY + (optMargin ?? 0)

    self.frame.origin = CGPoint(x: x, y: y)
  }

  @discardableResult func placeAbove(_ bottomView: UIView,
                                     withMargin optMargin: CGFloat? = nil,
                                     x optX: CGFloat? = nil) -> UIView {
    let x = optX ?? self.frame.origin.x
    let y = bottomView.frame.minY - self.frame.height - (optMargin ?? 0)

    self.frame.origin = CGPoint(x: x, y: y)

    return self
  }

  func placeAbove(_ bottomView: UIView,
                  centeredTo centerToView: UIView,
                  withMargin optMargin: CGFloat? = nil) {
    let centerX = centerToView.frame.midX - (self.frame.width / 2)
    let y = bottomView.frame.minY - self.frame.height - (optMargin ?? 0)

    self.frame.origin = CGPoint(x: centerX, y: y)
  }

  /**
   * Makes this view the same size as `sizeToView`
   */
  @discardableResult func resizeTo(_ sizeToView: UIView) -> UIView {
    var frame = self.frame
    frame.size.height = sizeToView.frame.height
    frame.size.width = sizeToView.frame.width

    self.frame = frame

    return self
  }

  /**
   * Centers the view on the x axis
   */
  @discardableResult func centerX(toView optView: UIView? = nil) -> UIView {
    // default to superview if no second view to center on is supplied
    let optView = optView ?? self.superview
    guard let view = optView else {
      print("No super view or other view to center on, cannot centerX for view")
      return self
    }

    self.center = CGPoint(x: view.frame.midX, y: self.frame.midY)

    return self
  }
}

Now my layout code looks as follows:

/**
 * Repositions views accordingly, without using constraints
 */
override func viewWillLayoutSubviews() {
  // point positioned label is static from the top,
  // if it wasn't I couldn't call it a point positioned view anymore :|
  self.pointPositionedLabel.frame.origin = CGPoint(x: 160, y: 70)

  // the framed label is basically tied to the nav bar
  // with a set x coordinate.
  self.framedLabel.placeBelow(self.navigationController!.navigationBar,
                              withMargin: 6,
                              x: 50)

  if UIApplication.shared.statusBarOrientation == .portrait {
  self.centerPositionedLabel.isHidden = false
  // the center positioned label goes below the framedLabel
  // if we're in landscape, that obfuscates the instructions label and can't touch this button
  // so if we are in landscape, don't show it
  self.centerPositionedLabel.placeAbove(self.instructionsLabel,
                                        centeredTo: self.view,
                                        withMargin: k.VIEW_MARGIN)
  }
  else {
    self.centerPositionedLabel.isHidden = true
  }

  // instructions label is center aligned
  self.instructionsLabel.center = self.view.center

  // can't touch this button goes below the instructions label.
  self.cantTouchThisButton.placeBelow(self.instructionsLabel,
                                      centeredTo: self.view,
                                      withMargin: k.VIEW_MARGIN)
}

Not perfect yet, but much better. I still have to go over the method naming and really hammer it out so that the method names make sense. I think there may be some ambiguity in saying withMargin: because it’s not always clear where the margin is.

I also implemented these originally to return a reference of self for fluent interface style method chaining. Which required the addition of the @discardableResult prefix to suppress Unused Result Warnings. This is something I may also want to drop all together. While it very convenient I’m not sure what performance impact changing the view’s frame repeatedly would have. Obviously people could still call the methods separtely if they wanted to, but I feel that having the method chaining would only encourage that behavior.

Locking Rotation, Altogether

If you want to lock out screen rotation completely you will need to override a get-only property of the UIViewController called shouldAutorotate, which returns a Bool:

open override var shouldAutorotate: Bool {
  return false
}

Now, if you’re using a UINavigationController, this won’t work on its own. You’ll need to extend UINavigationController to use whatever the current visible view controller says to do:

extension UINavigationController {
  open override var shouldAutorotate: Bool {
    return visibleViewController?.shouldAutorotate ?? true
  }
}

I set the default to true if there is no visible view controller because I am assuming allowing rotation is the default UINavigationController behavior.

If you wanted to apply this to all views across the entire app you could make the same extension to UIViewController. There’s also a way to do it through the plist file but since the topic is about how to move away from crazy Apple XML nonsense, I figure it’s cleaner and more obvious to have it in code.