How can I detect UIWebView reaching the top or bottom? Because I need to trigger an action when I reach the bottom.
So is that doable?
First of all, you should not put your UIWebView
inside a UIScrollView
as mentionned in the UIWebView
documentation.
Important: You should not embed UIWebView or UITableView objects in UIScrollView objects. If you do so, unexpected behavior can result because touch events for the two objects can be mixed up and wrongly handled.
Instead, you can access the UIScrollView
through the UIWebView
properties. Your view controller can implement the UIScrollViewDelegate
.
@interface MyViewController : UIViewController<UIScrollViewDelegate>
@end
Then you can hook to the UIScrollView:
- (void)viewDidLoad
{
[super viewDidLoad];
// Set self as scroll view protocol
webView.scrollView.delegate = self;
}
Then finally detect the top and bottom being reached:
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
if(scrollView.contentOffset.y
>=
(scrollView.contentSize.height - scrollView.frame.size.height)){
NSLog(@"BOTTOM REACHED");
}
if(scrollView.contentOffset.y <= 0.0){
NSLog(@"TOP REACHED");
}
}
Voila, you can detect when top and bottom are reached.
You can give this a shot -
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
if(scrollView == yourWebView)
{
int percentScrolled = abs((int)ceil((scrollView.contentOffset.y/scrollView.contentSize.height)*100));
if(percentScrolled > 100 || percentScrolled < 0)
percentScrolled = 0;
if(percentScrolled > 90)
{
//scroll percent is 90. do your thing here.
}
}
return;
}
What is being done here is everytime user scrolls webView, calculate the % scrolled & when the % scrolled is coming to end (say anything > 90%) do whatever you planned to do.
If you're targeting iOS 5, UIWebView
has a read-only scrollView
property that allows you to access the underlying UIScrollView
.
From there, you can hook into the scrollView's scrollViewDidScroll:
delegate method to receive information on scroll events.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With