Alexander Anikin's blog

My personal blog

Archive for February 2013

How to implement Scroll To Top functionality for UIWebView in Monotouch

leave a comment »

Someone can say – this is by default! But I have a case when it’s not.

Imagine – we have a UIWebView within content and it’s almost full fills screen size without needs to be scrolled. But content inside scrolling using Javascript (something like iScroll extension). So iOS thinking: “I shouldn’t  scroll anything for this view.”.  I this case you’ll never get scroll to top event. It’s not firing!

But I found a workaround for this issue. All you need to do just:

1.  Create a fullscreen ScrollView with content size much greater than screen size  – let iOS thinks: “I should support scrolling for this huge view”.

2. Put you UIWebView at random number of pixel below the top of the screen.

3. Switch off handling of ScrollToTop for UIWebView.ScrollView. This must be done because if two controls handle ScrollToTop – nothing works.

4. SetContentOffset to this random number of pixes – to make you UIWebView looks like it placed full-screen.

5. Create ScrollViewDelegate to handle firings of ScrollToTop Event.

That’s it!

Here is the sample code:

const int scrollOffset = 100;

var contentSize = new SizeF (320, 3000);

var scrollToPoint = new PointF (0, scrollOffset);

ScrollView = new UIScrollView();

UI = new DesignedFileManager(Settings);

// UI placed 100px (scrollOffset) lower than top of the screen

UI.Frame = new RectangleF(0, scrollOffset, Window.Frame.Width, Window.Frame.Height+scrollOffset);

// this lines must be there because iOS can’t choose who will support scrolling to top

// so UI web view will not handle scroll to top

UI.ScrollView.ScrollEnabled = false;

UI.ScrollView.ScrollsToTop = false;

// set scroll view frame like window frame

ScrollView.Frame = Window.Frame;

// let scrollview handle scrolling to top

ScrollView.ScrollEnabled = true;

ScrollView.ScrollsToTop = true;

// set scroll view content size bigger than window frame to support scrolling

ScrollView.ContentSize = contentSize;

ScrollView.ShowsVerticalScrollIndicator = false;

ScrollView.ShowsHorizontalScrollIndicator = false;

// scroll to 100px lower, so wevview fills full screen

ScrollView.SetContentOffset(scrollToPoint, false);

ScrollView.AutoresizingMask = UIViewAutoresizing.FlexibleHeight | UIViewAutoresizing.FlexibleWidth;

ScrollView.Delegate = new ScrollViewDelegate(UI);

ScrollView.AddSubview(UI);

_mainView.AddSubview(ScrollView);

And delegate:

class ScrollViewDelegate : UIScrollViewDelegate

{

DesignedFileManager UI;

public ScrollViewDelegate(DesignedFileManager ui) : base()

{

UI = ui;

}

public override bool ShouldScrollToTop(UIScrollView scrollView)

{

Trace.WriteLine(“Scroll to Top invoked.”);

UI.ScrollToTop();

return false;

}

}

Advertisements

Written by Alex Anikin

February 15, 2013 at 6:45 am

Posted in iOS, Mac, Monodevelop, Monotouch