detect changes to UIWebView's scroll view's contentSize

后端 未结 2 1312
南旧
南旧 2020-12-25 15:38

I\'m trying to set a UIView at the bottom of the content of a UIScrollView, do to so I set the view\'s position to the scrollview\'s contentsize height. But my scrollview is

2条回答
  •  独厮守ぢ
    2020-12-25 16:05

    Perhaps you can use key-value observing (KVO) to detect changes to the content size. I haven't tried it, but the code should look like this:

    static int kObservingContentSizeChangesContext;
    
    - (void)startObservingContentSizeChangesInWebView:(UIWebView *)webView {
        [webView.scrollView addObserver:self forKeyPath:@"contentSize" options:0 context:&kObservingContentSizeChangesContext];
    }
    
    - (void)stopObservingContentSizeChangesInWebView:(UIWebView *)webView {
        [webView.scrollView removeObserver:self forKeyPath:@"contentSize" context:&kObservingContentSizeChangesContext];
    }
    
    - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
        if (context == &kObservingContentSizeChangesContext) {
            UIScrollView *scrollView = object;
            NSLog(@"%@ contentSize changed to %@", scrollView, NSStringFromCGSize(scrollView.contentSize));
        } else {
            [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
        }
    }
    

    If that doesn't work, you may need to swizzle the setContentSize: method. Method swizzling lets your replacement method call the original method, which is what you need to do to pass the new content size on to the scroll view.

    You can read more about method swizzling here: http://www.mikeash.com/pyblog/friday-qa-2010-01-29-method-replacement-for-fun-and-profit.html

    I think this is the most popular code for swizzling: https://github.com/rentzsch/jrswizzle

提交回复
热议问题