Created
November 29, 2016 13:47
-
-
Save MP0w/5983b3c9cce4f1c1fddedf7cfbbc8249 to your computer and use it in GitHub Desktop.
A `UIScrollView` subclass that adapts its `intrinsicContentSize` to its `contentSize`
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
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