- Place a scrollview where you need in your viewcontroller as normal
- Change its subclass to IKScrollView
- Add a 'free floating' UIView to use as the content inside the scrollview (i.e. not part of the main view hierarchy)
- Add elements to your content view and configure with autolayout as you would normally (make it as tall or wide as needed)
- Connect the
contentView
IBOutlet from the IKScrollView to your content view - Optionally, set the type of size matching you want the content view to use (default is width)
- ...enjoy your scrolling interface
Last active
November 18, 2021 16:34
-
-
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...
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment