scalesPageToFit broken on UIWebView after keyboard is shown?

吃可爱长大的小学妹 提交于 2019-12-05 14:54:45

Seems to be a bug with Apple's private class UIDocumentView. For what ever reason viewportConfigurationsDidChange gets stuck on a zoom scale after the keyboard is activated, which is set by calling _setDocumentScale. When it's supposed to change to 1.333, for example, it gets stuck on 1.0.

It's "fixable" by writing a category for UIWebDocumentView, which is a subclass of UIDocumentView that doesn't implement these methods (so you can call the super's).

Despite my best efforts I couldn't find a way to fix this using the public API. I tried messing with the UIScrollView's zoom level, but I could never get that to work correctly. The content would get shifted, and other weird things would happen. Even tried doing it with JavaScript.

So the only way to fix it is through category on private classes.

This would never be approved in the app store.

So until Apple fixes this, SOL.

WARNING: this solution uses private APIs. Any app that uses this code might be rejected from the app store. I am posting it so people at least have a working solution.

@interface UIWebDocumentView : UIView
- (void)_setDocumentScale:(float)scale;
@end

@interface UIWebView (DocumentView)
- (UIWebDocumentView *)_documentView;
@end

- (void)resetScale:(UIWebView *)webView
{
    UIWebDocumentView *webDocumentView = [webView _documentView];
    CGFloat contentWidth = [[webView stringByEvaluatingJavaScriptFromString:@"document.body.scrollWidth;"] floatValue];
    CGSize viewSize = webView.bounds.size;
    float scale = viewSize.width / contentWidth;
    [webDocumentView _setDocumentScale:scale];
}

Call resetScale after the bounds of the web view change.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!