iOS Guides | Samples

MonoTouch.UIKit.UIScrollView Class

A UIView that can scroll, pan, and page its children.

See Also: UIScrollView

Syntax

[MonoTouch.Foundation.Register("UIScrollView", true)]
public class UIScrollView : UIView

Remarks

The UIScrollView class is a container that provides scrolling, zooming, and panning functionality of its content view. Because the UIScrollView class provides out-of-the-box functionality for scrolling and paging, it is generally used as the basis for UIViews whose content is larger than the UIScrollView's UIView.Frame. The need for and range of scrolling is specified by the application developer setting the UIScrollView's UIScrollView.ContentSize to a SizeF greater than the UIScrollView's UIView.Frame.

The most common ways to use the UIScrollView are to either:

Using A Single Large Subview

The following image, drawn from the "Scroll View" demo in the "iOS Standard Controls" sample, illustrates the simplest use-case: a single large subview (in this case, a UIImageView) whose image size matches the UIScrollView's UIScrollView.ContentSize. The UIScrollView.ContentOffset of the UIScrollView corresponds to the image pixel showing at the origin of the UIImageView (e.g., PointF [215, 145]). The UIScrollView.ContentSize of the UIScrollView defines the scroll limits. When the UIScrollView.ContentSize is larger than the UIScrollView's UIView.Frame, one gets scrolling behavior. If UIScrollView.ContentSize is not set or is set to too small a RectangleF, one doesn't (however, UIScrollView.AlwaysBounceVertical and UIScrollView.AlwaysBounceHorizontal can be used to allow dragging even in this situation.)

As the following code shows, it's straightforward to create and use a UIScrollView in this manner. The imageView is initialized from a file. The UIScrollView's UIScrollView.ContentSize is set to the size of the image (which happens to be 512 x 512 pixels and thus large enough to require scrolling unless zoomed out) and the imageView is added as a subview.

The delegate for the UIScrollView.ViewForZoomingInScrollView property allows the UIScrollView to automatically handle pinch-to-zoom gestures:

C# Example

// create our scroll view
scrollView = new UIScrollView (
new RectangleF (0, 0, this.View.Frame.Width, this.View.Frame.Height - this.NavigationController.NavigationBar.Frame.Height));
this.View.AddSubview (scrollView);

// create our image view
imageView = new UIImageView (UIImage.FromFile ("Images/Icons/512_icon.png"));
scrollView.ContentSize = imageView.Image.Size;
scrollView.MaximumZoomScale = 3f;
scrollView.MinimumZoomScale = .1f;
scrollView.AddSubview (imageView);

scrollView.ViewForZoomingInScrollView += (UIScrollView sv) => { return imageView; };

The UIScrollView tracks the location of the application-user's fingers and updates the UIScrollView's UIScrollView.ContentSize and UIScrollView.ZoomScale as they drag, swipe, and make pinch-to-zoom gestures. The UIScrollView draws the briefly-visible scroll-location indicators, shows the content clipped from its subviews, and animates the scrolling, panning, and zooming transitions. As the gesture or animation proceeds, the UIScrollView adjusts the UIScrollView.ContentOffset and UIScrollView.ZoomScale appropriately and repeatedly fires the UIScrollView.Scrolled event.

Panning and Paging

The next image, from the "Page Control" demo in the iOS Standard Controls sample, illustrates multiple subviews aligned within the boundaries of the UIScrollView's UIScrollView.ContentSize. The illustration shows the application in the middle of a swiping animation; portions of both the white and gray subviews are visible.

If UIScrollView.PagingEnabled is set to true or if the gesture attempts to scroll to an area outside the UIScrollView's UIScrollView.ContentSize, at the end of the gesture the selected subview will "bounce" into alignment with the UIScrollView's UIView.Frame.

It is up to the application developer to synchronize with the UIPageControl if one is used. A common way to do this is to handle the UIScrollView's UIScrollView.Scrolled event and change the model value that is observed by the UIPageControl (or one can imperatively set the UIPageControl's UIPageControl.CurrentPage).

In the paging demo, the UIView.Frames of the individual subviews and the UIScrollView.ContentSize of the UIScrollView are calculated, aligned, and set using the following code, taken from the "iOS Standard Controls" sample:

C# Example

// instantiate and add the controllers to our list
controllers.Add (new Controller_1 ());
controllers.Add (new Controller_2 ());
controllers.Add (new Controller_3 ());

for (int i = 0; i < controllers.Count; i++)
{
	// set their location and size, each one is moved to the 
	// right by the width of the previous
	RectangleF viewFrame = new RectangleF (
	scrlMain.Frame.Width * i,
	scrlMain.Frame.Y,
	scrlMain.Frame.Width,
	scrlMain.Frame.Height);
	controllers[i].View.Frame = viewFrame;

	// add the view to the scrollview
	scrlMain.AddSubview (controllers[i].View);
}

// set our scroll view content size (width = number of pages * scroll view width)
scrlMain.ContentSize = new SizeF (
scrlMain.Frame.Width * controllers.Count, scrlMain.Frame.Height);

Tap-To-Zoom

The "tap-to-zoom" gesture consists of the application user double-tapping the scrolling area. To enable this, the developer needs to create a UITapGestureRecognizer, configure it for two taps, give it a unique Selector, and add it to the UIScrollView. Then, the developer has to implement a method with an ExportAttribute configured to the Selector identifier.

The following code from the "Implement Tap-To-Zoom Recipe" shows the essential steps:

C# Example

UITapGestureRecognizer doubletap = new UITapGestureRecognizer();
doubletap.NumberOfTapsRequired = 2; // double tap
doubletap.AddTarget (this, new MonoTouch.ObjCRuntime.Selector("DoubleTapSelector"));
scrollView.AddGestureRecognizer(doubletap); // detect when the scrollView is double-tapped
//...etc...

[MonoTouch.Foundation.Export("DoubleTapSelector")]
public void OnDoubleTap (UIGestureRecognizer sender) {
if (scrollView.ZoomScale >= 1)
   scrollView.SetZoomScale(0.25f, true);
else
   scrollView.SetZoomScale(2f, true);
}

Touch Delays Associated with UIScrollView

Because scrolling and zooming gestures can begin anywhere on the screen, the UIScrollView intercepts touch events and waits briefly to see if the application user is making a scrolling or zooming gesture. This introduces a small delay but the default behavior can be customized by overriding the UIScrollView's UIScrollView.TouchesShouldBegin and UIScrollView.TouchesShouldCancelInContentView methods.

Subview Frames

Although generally the UIView.Frames of the content UIViews are aligned with the extent of the UIScrollView's UIScrollView.ContentSize and each other, this is not a requirement. Setting the UIView.Frame so that it extends beyond the boundaries of the UIScrollView.ContentSize may make drawing geometry easier or more consistent. If, by misaligning subviews, one displays an area within the UIScrollView.ContentSize of the UIScrollView that does not contain a UIView, gestures for scrolling and zooming occurring in the blank area will not work: the application must have an underlying UIView to get the expected behavior.

Some domains, such as maps and gameboards, may seem to suggest a design in which a UIScrollView has a large number of tiled subviews. However, all subviews -- whether visible or not -- are rendered and this can be resource- and processor-intensive. In such cases, it is the application developer's responsibility to add or remove subviews appropriately.

Event Sequence

The following illustration shows the user actions and resulting UIScrollView event sequence associated with a dragging or swiping gesture:

The following illustration shows the user actions and resulting UIScrollView event sequence associated with a pinch-to-zoom gesture:

State Preservation and Restoration

In iOS 6 or later, if the UIView.RestorationIdentifier property is set, on restoration the UIScrollView's UIScrollView.ZoomScale, UIScrollView.ContentOffset, and UIScrollView.ContentInset properties will be restored.

Event-handling

The MonoTouch API supports two styles of event notification: the Objective-C style that uses a delegate class or the C# style using event notifications.

The C# style allows the user to add or remove event handlers at runtime by assigning to the events of properties of this class. Event handlers can be anyone of a method, an anonymous methods or a lambda expression. Using the C# style events or properties will override any manual settings to the Objective-C Delegate or UIScrollView.WeakDelegate settings.

The Objective-C style requires the user to create a new class derived from UIScrollViewDelegate class and assign it to the UIScrollView.Delegate property. Alternatively, for low-level control, by creating a class derived from NSObject which has every entry point properly decorated with an [Export] attribute (see ExportAttribute). The instance of this object can then be assigned to the UIScrollView.WeakDelegate property.

Related content

Requirements

Namespace: MonoTouch.UIKit
Assembly: monotouch (in monotouch.dll)
Assembly Versions: 0.0.0.0

The members of MonoTouch.UIKit.UIScrollView are listed below.

See Also: UIView

Public Constructors

Default constructor that initializes a new instance of this class with no parameters.
A constructor that initializes the object from the data stored in the unarchiver object.
Constructor to call on derived classes to skip initialization and merely allocate the object.
Initializes the UIScrollView with the specified frame.
A constructor used when creating managed representations of unmanaged objects; Called by the runtime.

Public Properties

AlwaysBounceHorizontalBoolean. If set to true and UIScrollView.Bounces is true, then bouncing will occur when horizontal scrolling reaches the end of the view.
AlwaysBounceVerticalBoolean. If set to true and UIScrollView.Bounces is true, then bouncing will occur when vertical scrolling reaches the end of the view.
[read-only]
static
AppearanceUIScrollView+UIScrollViewAppearance. Strongly-typed property that returns the UIAppearance class for this class.
BouncesBoolean. If set to true, then the scroll view will bounce at a content boundary.
BouncesZoomBoolean. If set to true and UIScrollView.Bounces is true, then the scroll view will bounce around a zoom limit once zooming has exceeded that limit.
CanCancelContentTouchesBoolean. If set to false, then the scroll view will not scroll as a result of finger movement once the tracking has started in the content view.
[read-only]
override
ClassHandleIntPtr. The handle for this class.
ContentInsetUIEdgeInsets. The distance, in points, that the content of the scroll view is inset inside of the scroll view.
ContentOffsetPointF. The offset for the origin of the content inside of a scroll view, relative to the origin of the scroll view itself.
ContentSizeSizeF. The size of the content view, as measured in points.
[read-only]
DeceleratingBoolean. If this property returns true, then scrolling is still occuring in the scroll view but the user is not dragging their finger.
DecelerationRateSingle. This property returns a value that represents the deceleration rate once the user lifts their finger. There are two values, UIScrollView.DecelerationRateFast and UIScrollView.DecelerationRateNormal, that can serve as reference points for deceleration rates.
[read-only]
static
DecelerationRateFastSingle. Represents the value associated with the constant UIScrollViewDecelerationRateFast
[read-only]
static
DecelerationRateNormalSingle. Represents the value associated with the constant UIScrollViewDecelerationRateNormal
DelaysContentTouchesBoolean. Specifies whether the UIScrollView can delay input to attempt to determine if a scrolling gesture has been made
DelegateUIScrollViewDelegate. An instance of the MonoTouch.UIKit.UIScrollViewDelegate model class which acts as the class delegate.
DirectionalLockEnabledBoolean. If true, and the user begins scrolling in one axis (i.e. horizontally) then the scroll view disables scrolling in the other axis (i.e. vertically).
[read-only]
DraggingBoolean. Returns true if the content has begun scrolling. Read-only.
IndicatorStyleUIScrollViewIndicatorStyle. The style of the scroll indicators.
KeyboardDismissModeUIScrollViewKeyboardDismissMode. The manner in which the keyboard is dismissed at the start of dragging.
MaximumZoomScaleSingle. The value of the maximum scale factor that can be applied to the content view.
MinimumZoomScaleSingle. The value of the minimum scale factor that can be applied to the content view.
PagingEnabledBoolean. If true then scrolling will stop on paging boundaries of the content view; scrolling occurs a page at a time.
[read-only]
PanGestureRecognizerUIPanGestureRecognizer. The gesture recognizer for pan gestures. Read-only.
[read-only]
PinchGestureRecognizerUIPinchGestureRecognizer. The gesture recognizer for pinch gestures. Read-only.
RefreshControlUIRefreshControl. If not null, the UIRefreshControl used to update the view contents.
ScrollEnabledBoolean. If set to true then scrolling is enabled.
ScrollIndicatorInsetsUIEdgeInsets. How far inset the scroll indicators are from the scroll view's edges.
ScrollsToTopBoolean. If true, then the scroll view will jump to the top of the content when the user taps on the status bar.
ShouldScrollToTopUIScrollViewCondition. Delegate invoked by the object to get a value.
ShowsHorizontalScrollIndicatorBoolean. If true, then the horizontal scroll bar will be visible when tracking.
ShowsVerticalScrollIndicatorBoolean. If true, then the vertical scroll bar will be visible when tracking.
[read-only]
TrackingBoolean. Returns true if the user has touched the content and scrolling is about to begin.
ViewForZoomingInScrollViewUIScrollViewGetZoomView. Delegate invoked by the object to get a value.
WeakDelegateNSObject. An object that can respond to the delegate protocol for this type
[read-only]
ZoomBouncingBoolean. Returns true if the scroll view is bouncing back to the zoom scaling limits specified byUIScrollView.MinimumScrollView and UIScrollView.MaximumScrollView. Read-only.
[read-only]
ZoomingBoolean. Returns true if the content view is zooming in or out. Read-only.
ZoomScaleSingle. The scale factor that is being applied to the content of a scroll view.

Public Methods

static
AppearanceWhenContainedIn(params Type[]) : UIScrollView+UIScrollViewAppearance
Returns a strongly typed UIAppearance for instances of this class when the view is hosted in the specified hierarchy.
FlashScrollIndicators()
This method will flash the scroll indicators for a short time.
static
GetAppearance(UITraitCollection) : UIScrollView+UIScrollViewAppearance
Returns an appearance proxy for the specified traits.
static
GetAppearance(UITraitCollection, params Type[]) : UIScrollView+UIScrollViewAppearance
Returns an appearance proxy for the specified traits when found in the containers containment hierarchy.
static
GetAppearance<T>() : UIScrollView+UIScrollViewAppearance
Obtains the appearance proxy UIScrollViewAppearance for the subclass of UIScrollView.
static
GetAppearance<T>(UITraitCollection) : UIScrollView+UIScrollViewAppearance
Obtains the appearance proxy UIScrollViewAppearance for the subclass of UIScrollView.
static
GetAppearance<T>(UITraitCollection, params Type[]) : UIScrollView+UIScrollViewAppearance
Obtains the appearance proxy UIScrollViewAppearance for the subclass of UIScrollView that has the specified trait collection when the view is hosted in the specified hierarchy.
ScrollRectToVisible(RectangleF, Boolean)
This method will scroll the content view so that the area defined by rect is visible.
SetContentOffset(PointF, Boolean)
This method will move the scroll view to a new location, with optional animation.
SetZoomScale(Single, Boolean)
This value should be between the values of UIScrollView.MinimumZoomFactor and UIScrollView.MaximumZoomFactor.
TouchesShouldBegin(NSSet, UIEvent, UIView) : Boolean
This method is provided so that the behaviour of a touch in the content view may be customized by a subclass.
TouchesShouldCancelInContentView(UIView) : Boolean
This method controls if the touches of a content subview should be cancelled, which would allow dragging to start.
ZoomToRect(RectangleF, Boolean)
This method will zoom the area defined by rect so that it is visible in the content view.

Protected Methods

override
Dispose(Boolean)
Releases the resources used by the UIScrollView object.

Public Events

DecelerationEndedEvent raised by the object.
DecelerationStartedEvent raised by the object.
DidZoomEvent raised by the object.
DraggingEndedEvent raised by the object.
DraggingStartedEvent raised by the object.
ScrollAnimationEndedEvent raised by the object.
ScrolledEvent raised by the object.
ScrolledToTopEvent raised by the object.
WillEndDraggingEvent raised by the object.
ZoomingEndedEvent raised by the object.
ZoomingStartedEvent raised by the object.