有人知道如何阻止UIWebView垂直反弹吗?我的意思是,当用户触摸他们的iphone屏幕,向下拖动他们的手指时,web视图在我加载的网页上方显示一个空白点?

我研究了以下可能的解决方案,但没有一个适合我:

http://www.iphonedevsdk.com/forum/iphone-sdk-development/996-turn-off-scrolling-bounces-uiwebview.html

http://forums.macrumors.com/showthread.php?t=619534

我如何停止一个UIScrollView水平反弹?


当前回答

在Swift中禁用反弹

webViewObj.scrollView.bounces = false

其他回答

布拉德的方法对我很管用。如果你使用它,你可能想让它更安全一点。

id scrollView = [yourWebView.subviews objectAtIndex:0];
if( [scrollView respondsToSelector:@selector(setAllowsRubberBanding:)] )
{
    [scrollView performSelector:@selector(setAllowsRubberBanding:) withObject:NO];
}

如果苹果改变了一些东西,那么反弹就会回来-但至少你的应用程序不会崩溃。

我很恼火地发现UIWebView不是一个滚动视图,所以我做了一个自定义子类来获得web视图的滚动视图。这个子类包含一个滚动视图,所以你可以自定义你的web视图的行为。这门课的妙语是:

@class CustomWebView : UIWebview
...

- (id) initWithFrame:(CGRect)frame{
self = [super initWithFrame:frame];
// WebViews are subclass of NSObject and not UIScrollView and therefore don't allow customization.
// However, a UIWebView is a UIScrollViewDelegate, so it must CONTAIN a ScrollView somewhere.
// To use a web view like a scroll view, let's traverse the view hierarchy to find the scroll view inside the web view.
for (UIView* v in self.subviews){
    if ([v isKindOfClass:[UIScrollView class]]){
        _scrollView = (UIScrollView*)v; 
        break;
    }
}
return self;

}

然后,当你创建一个自定义web视图时,你可以禁用反弹:

customWebView.scrollView.bounces = NO; //(or customWebView.scrollView.alwaysBounceVertically = NO)

这是一个伟大的通用方法,使web视图具有自定义滚动行为。这里有几件事需要注意:

as with any view, you'll also need to override -(id)initWithCoder: if you use it in Interface Builder when you initially create a web view, its content size is always the same as the size of the view's frame. After you scroll the web, the content size represents the size of the actual web contents inside the view. To get around this, I did something hacky - calling -setContentOffset:CGPointMake(0,1)animated:YES to force an unnoticeable change that will set the proper content size of the web view.

for (id subview in webView.subviews)
  if ([[subview class] isSubclassOfClass: [UIScrollView class]])
    ((UIScrollView *)subview).bounces = NO;

...似乎工作得很好。

它也将被App Store接受。

更新:在iOS 5。x+有一个更简单的方法- UIWebView有scrollView属性,所以你的代码可以看起来像这样:

webView.scrollView.bounces = NO;

WKWebView也是一样。

我所做的就是:

UIView *firstView = [webView.subviews firstObject];

if ([firstView isKindOfClass:[UIScrollView class]]) {

    UIScrollView *scroll = (UIScrollView*)firstView;
   [scroll setScrollEnabled:NO];  //to stop scrolling completely
   [scroll setBounces:NO]; //to stop bouncing 

}

对我来说很好… 此外,如果你在这个问题中使用这个选项,苹果会拒绝它 你的iPhone应用。

在iOS5上,只有当你计划让用户缩放webview内容(我:双击),反弹设置是不够的。你还需要设置alwaysBounceHorizontal和alwaysBounceVertical属性为NO,否则当它们缩小时(另一个双击…)默认它将再次反弹。