我可以通过在 WebView 的 scrollView 的顶部和底部添加白色子视图来做到这一点。我控制 WebView 的内容,所以我知道白色是可以的 - 如果你正在加载任意内容,这将不起作用。
// _topCover and _bottomCover are ivar UIViews
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
// with cover views 300pt high, I couldn't scroll far enough to see the shadow,
// even in portrait on an iPad, which gives you the longest scroll distance
CGFloat coverage = 300;
_topCover = [[UIView alloc] initWithFrame:CGRectMake(0, -coverage, webView.bounds.size.width, coverage)];
_bottomCover = [[UIView alloc] initWithFrame:CGRectMake(0, webView.scrollView.contentSize.height, webView.bounds.size.width, coverage)];
_topCover.backgroundColor = [UIColor whiteColor];
_bottomCover.backgroundColor = [UIColor whiteColor];
// in case the webView is resized, e.g. by rotating the device
_topCover.autoresizingMask = UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleWidth;
_bottomCover.autoresizingMask = UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleWidth;
[webView.scrollView addSubview:_topCover];
[webView.scrollView addSubview:_bottomCover];
}
我在页面加载后运行它,以便webView.scrollView.contentSize.height 会给我正确的高度。如果您的页面动态改变高度,我不确定这将如何工作。我的页面只加载一次;如果您正在重新加载,您将希望在第一次之后跳过在 _topCover 和 _bottomCover 上运行 alloc/init 以提高效率。
更新:当视图旋转时,我不确定我使用上面的autoresizingMask 是否足够。您可能需要将其放在包含您的UIWebView 的UIViewController 中,以便在旋转后调整封面大小:
- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation
{
CGFloat coverage = 300;
_topCover.frame = CGRectMake(0, -coverage, self.webView.bounds.size.width, coverage);
_bottomCover.frame = CGRectMake(0, self.webView.scrollView.contentSize.height, self.webView.bounds.size.width, coverage);
}