Skip to content

Instantly share code, notes, and snippets.

@IanKeen
Last active November 18, 2021 16:34
Show Gist options
  • Star 11 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save IanKeen/2a41e9f55311af1c20f2 to your computer and use it in GitHub Desktop.
Save IanKeen/2a41e9f55311af1c20f2 to your computer and use it in GitHub Desktop.
A UIScrollView subclass that allows you to use scrollviews and autolayout without the drama...
enum SizeMatching {
case Width, Height, Both, None
}
class IKScrollView: UIScrollView {
//MARK: - Outlets
@IBOutlet private var contentView: UIView?
//MARK: - Properties
@IBInspectable var sizeMatching = SizeMatching.Width
//MARK: - Lifecycle
override func layoutSubviews() {
super.layoutSubviews()
if let contentView = self.contentView {
if (contentView.superview != self) {
self.addSubview(contentView)
}
var size = contentView.bounds.size
switch self.sizeMatching {
case .Width: size.width = self.bounds.width
case .Height: size.height = self.bounds.height
case .Both: size.width = self.bounds.width; size.height = self.bounds.height
case .None: break
}
contentView.frame = CGRect(origin: CGPoint(x: 0, y: 0), size: size)
self.contentSize = size
}
}
}
  1. Place a scrollview where you need in your viewcontroller as normal
  2. Change its subclass to IKScrollView
  3. Add a 'free floating' UIView to use as the content inside the scrollview (i.e. not part of the main view hierarchy)
  4. Add elements to your content view and configure with autolayout as you would normally (make it as tall or wide as needed)
  5. Connect the contentView IBOutlet from the IKScrollView to your content view
  6. Optionally, set the type of size matching you want the content view to use (default is width)
  7. ...enjoy your scrolling interface
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment