Advertisement
Guest User

Untitled

a guest
Aug 3rd, 2015
144
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.52 KB | None | 0 0
  1. import Foundation
  2.  
  3. public class ObserverContext: NSObject {
  4. public let keyPath: String
  5. public let options: NSKeyValueObservingOptions
  6. public var context = 0
  7. public init(keyPath: String, options: NSKeyValueObservingOptions = nil) {
  8. self.keyPath = keyPath
  9. self.options = options
  10. }
  11. }
  12.  
  13. public extension NSObject {
  14.  
  15. public func addObserver(observer: NSObject, context: ObserverContext) {
  16. addObserver(observer, forKeyPath: context.keyPath, options: context.options, context: &context.context)
  17. }
  18.  
  19. public func removeObserver(observer: NSObject, context: ObserverContext) {
  20. removeObserver(observer, forKeyPath: context.keyPath, context: &context.context)
  21. }
  22.  
  23. }
  24.  
  25. // USAGE:
  26. class ViewController: UIViewController {
  27. private let contentSizeContext = ObserverContext(keyPath: "contentSize")
  28. private lazy var scrollView: UIScrollView = { return UIScrollView() }()
  29.  
  30. override func viewDidLoad() {
  31. super.viewDidLoad()
  32. scrollView.addObserver(self, context: contentSizeContext)
  33. }
  34.  
  35. override func observeValueForKeyPath(keyPath: String, ofObject object: AnyObject, change: [NSObject : AnyObject], context: UnsafeMutablePointer<Void>) {
  36. switch context {
  37. case &contentSizeContext.context:
  38. print(scrollView.contentSize)
  39. default:
  40. super.observerValueForKeyPath(keyPath, ofObject: object, change: change, context: context)
  41. }
  42.  
  43. deinit {
  44. if isViewLoaded() {
  45. scrollView.removeObserver(self, context: contentSizeContext)
  46. }
  47. }
  48. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement