Skip to content

Instantly share code, notes, and snippets.

@MP0w
Created November 29, 2016 13:47
Show Gist options
  • Save MP0w/5983b3c9cce4f1c1fddedf7cfbbc8249 to your computer and use it in GitHub Desktop.
Save MP0w/5983b3c9cce4f1c1fddedf7cfbbc8249 to your computer and use it in GitHub Desktop.
A `UIScrollView` subclass that adapts its `intrinsicContentSize` to its `contentSize`
import Foundation
import UIKit
/// A `UIScrollView` subclass that adapts its `intrinsicContentSize` to its `contentSize`
final class IntrinsicSizeAwareScrollView: UIScrollView {
private let keyPath = NSStringFromSelector(#selector(getter: contentSize))
override init(frame: CGRect) {
super.init(frame: frame)
addContentSizeObserver()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
addContentSizeObserver()
}
deinit {
removeObserver(self, forKeyPath: keyPath)
}
override func observeValue(forKeyPath keyPath: String?,
of object: Any?,
change: [NSKeyValueChangeKey : Any]?,
context: UnsafeMutableRawPointer?) {
if self.keyPath == keyPath {
if let new = change?[.newKey] as? NSValue,
let old = change?[.oldKey] as? NSValue,
new != old {
invalidateIntrinsicContentSize()
}
}
}
override var intrinsicContentSize: CGSize {
return contentSize
}
private func addContentSizeObserver() {
addObserver(self, forKeyPath: keyPath, options: [.new, .old], context: nil)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment