Fixing ListView Offset on Pull to Refresh in Xamarin iOS

Hey Guys!

Recently I came upon an issue using ListViews in iOS on Xamarin Forms with the pull to refresh feature enabled, that caused the first item in my listview to be scrolled off screen each time the refresh on the list completed.

Once I noticed this behavior, I began to think on ways we could solve this issue and found a good workaround we could use by creating a custom renderer on iOS for our list and basically resetting the scroll position on our list each time we refresh it, to guarantee it will start correctly each time.

Let’s get Started!🙌

I have decided to call my custom ListView, ExtendedListView you can name it whatever you like but for the sake of this post, this will be the name we will use to refer to this custom view. In this class is where we will be adding all the extra functionality we wish to support on my special listview throughout my app.

STEP 1 – CREATE CONTROLS FOLDERS AND ADD OUR NEW CLASS FILE

 It’s always good to keep our project nice and tidy. I personally like to create a new File Directory on the Shared Project (this can also apply to the iOS and Android project where needed), Called “Controls” inside this directory is where I create all my custom controls, your file structure should look like this now:

STEP 2 – CREATING OUR extendedListview RENDERER in ios project

The first thing we want to do is extend from the ListViewRenderer class and export our new renderer Xamarin forms renderer to our assembly since we are going to be modifying the normal behavior of the ListView Xamarin Forms component:

STEP 3 – ADDING OUR CUSTOM BEHAVIOR

Now that we have our custom renderer, we just need to make it set the offset of our list to 0,0, each time we refresh our collection of items and to do that we will override the OnElementPropertyChanged method and each time that the IsRefreshing property is set to false we will reset the offset of our list:

Ce finito Guys! Now we have our Listview working again each time we refresh our list, Great job! you can now see how we can leverage custom renderers to add custom behavior to our Xamarin Forms components and react differently to changes on them.

Made with ❤ by Pujols.


Good References to learn more about custom renderers

Creating Custom Renderers – Microsoft Docs

https://docs.microsoft.com/en-us/xamarin/xamarin-forms/app-fundamentals/custom-renderer/

Customizing Listview – Microsoft Docs

https://docs.microsoft.com/en-us/xamarin/xamarin-forms/app-fundamentals/custom-renderer/listview

Credits for artwork components:
Mobile Icons for the banner of the post made by Freepik

(Visited 1,089 times, 1 visits today)

Leave A Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.