防止uiscrollview进一步滚动到特定点 [英] Prevent uiscrollview from scrolling further then certain point
问题描述
我有一个UIScrollView,该UIScrollView的子视图创建的内容的宽度约为7000. 现在,我希望UIScrollView不会再滚动到2000.
I have a UIScrollView which has subviews that create a content with a width of about 7000. Now I want the UIScrollView to not scroll any further then 2000.
我尝试过:
[scrollView setContentSize:CGSizeMake(768.0, 2000.0)];
[scrollView setClipsToBounds:YES];
但是我仍然可以滚动到末尾,如何防止这种情况发生?
But I can still scroll to the end, how do I prevent this?
推荐答案
页面加载后,似乎webView
正在更改其scrollView
contentSize
.
It's seems that webView
is changing its scrollView
contentSize
after page loading.
在您的init中将self设置为WebView
的委托:
In your init set self as a delegate of WebView
:
[webView setDelegate: self];
并添加此方法:
- (void)webViewDidFinishLoad: (UIWebView *)webView {
[webView.scrollView setContentSize: CGSizeMake(768.0, 2000.0)];
}
在我的测试用例中,它工作正常.
In my test case it's working fine.
已更新:
调用javascript方法有时不会触发webViewDidFinishLoad
.因此,最通用的技术将是键值观察.
Calling javascript methods sometimes does not trigger webViewDidFinishLoad
. So the most universal technique will be Key-Value Observing.
初始化:
[webView.scrollView addObserver:self forKeyPath:@"contentSize" options:NSKeyValueObservingOptionNew context:nil];
在此方法的某个地方:
- (void)observeValueForKeyPath:(NSString *)keyPath
ofObject:(id)object
change:(NSDictionary *)change
context:(void *)context
{
UIScrollView * scrlView = (UIScrollView *) object;
if ([keyPath isEqual:@"contentSize"]) {
NSLog(@"New contentSize: %f x %f",scrlView.contentSize.width,scrlView.contentSize.height);
if(scrlView.contentSize.width!=768.0||scrlView.contentSize.height!=2000.0)
[scrlView setContentSize:CGSizeMake(768.0, 2000.0)];
}
}
别忘了在取消分配的情况下删除观察者:
Do not forget to remove observer in case of dealloc:
[webView.scrollView removeObserver:self forKeyPath:@"contentSize"];
这篇关于防止uiscrollview进一步滚动到特定点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!