Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS : detect UIWebView reaching the top or bottom

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?

like image 865
Mohamed Emad Hegab Avatar asked Mar 02 '12 14:03

Mohamed Emad Hegab


3 Answers

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.

like image 81
gfrigon Avatar answered Nov 07 '22 08:11

gfrigon


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.

like image 23
Srikar Appalaraju Avatar answered Nov 07 '22 07:11

Srikar Appalaraju


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.

like image 20
gregheo Avatar answered Nov 07 '22 08:11

gregheo