hidden-username
hidden-username

Reputation: 2697

KVO - UIScrollView.contentSize false positive?

Using WKWebview, I am trying to monitor changes to the webView.scrollView.contentSize. The problem is that I am getting multiple notifications for the same size. Whenever I scroll, the notification is sent, even though the contentSize remains the same. I know I could solve this myself by just tracking previous size, in my handler, but I am not really confident in how KVO works under the hood and was worried that this could be expensive.

   let handler = {(scrollView: UIScrollView, change: NSKeyValueObservedChange<CGSize>) in
        if let contentSize = change.newValue {
            print ("ContentSize", contentSize)
        }
    }

    obs.insert(webView.scrollView.observe(\UIScrollView.contentSize, options: [NSKeyValueObservingOptions.new], changeHandler: handler))

Output: (generated from scrolling)

ContentSize (1366.0, 2061.0) ContentSize (1366.0, 2061.0) ContentSize (1366.0, 2061.0) ContentSize (1366.0, 2061.0)

I don't understand why this notification is being observed as the contentSize is not a new value. Am I misunderstanding something? Should I just store prevSize myself and check in the handler for changes?

Upvotes: 1

Views: 834

Answers (1)

appfigurate
appfigurate

Reputation: 136

The classes in UIKit generally don't support KVO, as described here:

https://developer.apple.com/library/content/documentation/General/Conceptual/DevPedia-CocoaCore/KVO.html

"Although the classes of the UIKit framework generally do not support KVO, you can still implement it in the custom objects of your application, including custom views."

Unless a class is documented as supporting KVO, you should assume that it does not (even if it appears to work). It may appear to work in one version of iOS, and not the next...

Upvotes: 2

Related Questions