Introduction
In this article, we will create a Xamarin iOS application that will create the slider view using the page control and scroll view. We will have a scroll view that will scroll the page horizontally and a page control that displays on which page we are currently in.
Prerequisite
- Programming in C#.
- The basics of Xamarin.
Implementation
Open Visual Studio Community Edition.
Select single view app and click "Next".
Give app name and click "Next".
Write the project and solution name and create the application.
Open main.storyboard.
Add a View from the toolpad to your view controller.
Drag the UiView to your controller.
Make it large by sliding it horizontally.
Set the name property to MyView.
Inside this view, add some labels. Suppose we add tree label.
Add three labels - the third label may not be visible because it is outside of the view controller.
This will be something like above, with three labels, change the text property of labels (“Page1”, “Page2”, “Page3”).
Great, now we have three labels inside view.
Now, add scroll view from the toolpad to your controller.
Add the scroll view by simply dragging it to your controller.
Now, drag the UiView having 3 labels inside this Scroll View.
Your document outline will become as following.
In the view hierarchy, your added view with three labels will come inside Scroll View after you drag it inside of it.
Once you are done and sure that your view is coming from the scroll view, let us set some properties of the scroll view.
Set the name to “MyScrollView”.
Set the Paging Enabled property on by checking it.
Now, add Page Control view from toolpad to your view controller.
Add this control by dragging it to your view controller.
Set the properties as below.
Set the Name property to “MyPager”.
Set the number of pages to 3.
set the tint color and Current page color.
Open viewController.cs and edit with below content.
- using System;
- using UIKit;
-
- namespace SliderShowApp {
- public partial class ViewController : UIViewController {
- protected ViewController(IntPtr handle) : base(handle) {
-
- }
-
- public override void ViewDidLoad()
- {
- base.ViewDidLoad();
- MyScrollView.ContentSize = MyView.Frame.Size;
- MyScrollView.Scrolled += (sender, e) => {
- MyPager.CurrentPage = (nint)(MyScrollView.ContentOffset.X / MyScrollView.Frame.Width);
- };
-
- }
-
- public override void DidReceiveMemoryWarning() {
- base.DidReceiveMemoryWarning();
-
- }
- }
- }
We have written the logic for scrolled, when user scrolls the data to left or right on the scroll view, then the current page will also be set accordingly.
Build and run the application.
Scroll left for page2.
You can see the current page and tint colors changed according to scrolled page content.