Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import Foundation
- public class ObserverContext: NSObject {
- public let keyPath: String
- public let options: NSKeyValueObservingOptions
- public var context = 0
- public init(keyPath: String, options: NSKeyValueObservingOptions = nil) {
- self.keyPath = keyPath
- self.options = options
- }
- }
- public extension NSObject {
- public func addObserver(observer: NSObject, context: ObserverContext) {
- addObserver(observer, forKeyPath: context.keyPath, options: context.options, context: &context.context)
- }
- public func removeObserver(observer: NSObject, context: ObserverContext) {
- removeObserver(observer, forKeyPath: context.keyPath, context: &context.context)
- }
- }
- // USAGE:
- class ViewController: UIViewController {
- private let contentSizeContext = ObserverContext(keyPath: "contentSize")
- private lazy var scrollView: UIScrollView = { return UIScrollView() }()
- override func viewDidLoad() {
- super.viewDidLoad()
- scrollView.addObserver(self, context: contentSizeContext)
- }
- override func observeValueForKeyPath(keyPath: String, ofObject object: AnyObject, change: [NSObject : AnyObject], context: UnsafeMutablePointer<Void>) {
- switch context {
- case &contentSizeContext.context:
- print(scrollView.contentSize)
- default:
- super.observerValueForKeyPath(keyPath, ofObject: object, change: change, context: context)
- }
- deinit {
- if isViewLoaded() {
- scrollView.removeObserver(self, context: contentSizeContext)
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement