Rupert  Beatty

Rupert Beatty

1667310793

An Easy Way to Use Pull To Refresh and infinite Scrolling in Swift

ESPullToRefresh is an easy-to-use component that give pull-to-refresh and infinite-scrolling implemention for developers. By extension to UIScrollView, you can easily add pull-to-refresh and infinite-scrolling for any subclass of UIScrollView. If you want to customize its UI style, you just need conform the specified protocol.

中文介绍

Requirements

  • Xcode 8 or later
  • iOS 8.0 or later
  • ARC
  • Swift 5.0 or later

Features

  • Support UIScrollView and its subclasses UICollectionView UITableView UITextView
  • Pull-Down to refresh and Pull-Up to load more
  • Support customize your own style(s)

Demo

Download and run the ESPullToRefreshExample project in Xcode to see ESPullToRefresh in action.

Installation

CocoaPods

pod "ESPullToRefresh"

Carthage

github "eggswift/pull-to-refresh"

Manually

git clone https://github.com/eggswift/pull-to-refresh.git
open ESPullToRefresh

Usage

Default style:

example_default.gif

Add ESPullToRefresh to your project

import ESPullToRefresh

Add default pull-to-refresh

self.tableView.es.addPullToRefresh {
    [unowned self] in
    /// Do anything you want...
    /// ...
    /// Stop refresh when your job finished, it will reset refresh footer if completion is true
    self.tableView.es.stopPullToRefresh(completion: true)
    /// Set ignore footer or not
    self.tableView.es.stopPullToRefresh(completion: true, ignoreFooter: false)
}

Add default infinite-scrolling

self.tableView.es.addInfiniteScrolling {
    [unowned self] in
    /// Do anything you want...
    /// ...
    /// If common end
    self.tableView.es.stopLoadingMore()
    /// If no more data
    self.tableView.es.noticeNoMoreData()
}

Customize Style

As effect:

example_meituan.gif

PS: Load effect is from MeiTuan iOS app.

example_wechat.gif

Customize refresh need conform the ESRefreshProtocol and ESRefreshAnimatorProtocol protocol.

Add customize pull-to-refresh

func es.addPullToRefresh(animator animator: protocol<ESRefreshProtocol, ESRefreshAnimatorProtocol>, handler: ESRefreshHandler)

Add customize infinite-scrolling

func es.addInfiniteScrolling(animator animator: protocol<ESRefreshProtocol, ESRefreshAnimatorProtocol>, handler: ESRefreshHandler)

Espried and auto refresh

ESPullToRefresh support for the latest expiration time and the cache refresh time, You need set an refreshIdentifier to your UIScrollView.

scrollView.refreshIdentifier = "Your Identifier" // Set refresh identifier
scrollView.expriedTimeInterval = 20.0 // Set the expiration interval

You can use es.autoPullToRefresh() method, when the time over the last refresh interval expires automatically refreshed.

scrollView.es.autoPullToRefresh()

let expried = scrollView.espried // expired or not

Remove

func es.removeRefreshHeader()
func es.removeRefreshFooter()

Sponsor

You can support the project by checking out our sponsor page. It takes only one click:

git-adThis advert was placed by GitAds

Download Details:

Author: Eggswift
Source Code: https://github.com/eggswift/pull-to-refresh 
License: MIT license

#swift #webview #infinite #collectionview 

An Easy Way to Use Pull To Refresh and infinite Scrolling in Swift
Diego  Elizondo

Diego Elizondo

1652528760

Reducir el espacio entre celdas de CollectionView

Cuando abrimos la galería de un iPhone vemos que las imágenes están estructuradas como una cuadrícula que tiene filas y columnas. CollectionView en el desarrollo de iOS es similar a esa estructura. Nos proporciona una funcionalidad que podemos mostrar elementos en forma de cuadrícula, es similar a TableView pero tenemos más funcionalidad en CollectionView para mostrar los elementos, podemos mostrar los elementos en varias filas y columnas y podemos desplazarlos horizontalmente o verticalmente

Podemos ver en este ejemplo donde tenemos un CollectionView que tiene imágenes de gatos, estas imágenes están estructuradas como una cuadrícula, podemos desplazarnos hacia abajo. Según la documentación de Apple Developer, CollectionView es un objeto que administra una colección ordenada de elementos de datos y los presenta mediante diseños personalizables. Cada elemento de CollectionView se denomina celda, ya que en este ejemplo cada imagen de un gato se presenta en una celda.

CollectionView obtiene datos de un objeto llamado DataSource que se almacenan en la propiedad DataSource de CollectionView. Podemos crear un objeto DataSource personalizado mediante el protocolo UICollectionViewDataSource.

Comencemos con el Xcode

Abra Xcode y cree una aplicación de vista única, nombre el proyecto y haga clic en siguiente y estamos listos para comenzar.

Vaya al archivo main.storyboard para buscar collectionView y simplemente arrastre y suelte CollectionView en nuestro guión gráfico y establezca todas las restricciones en cero. Aquí puede ver un CollectionView agregado a nuestro guión gráfico y en el lado izquierdo puede ver un CollectionView agregado. Aquí, de forma predeterminada, se agrega un tipo CollectionViewCell de UICollectionView a CollectionView. En esta CollectionViewCell se agrega una vista de contenido, es un lugar donde guardamos nuestros elementos o contenido.

Ahora, en el lado derecho, vaya al nombre del inspector de atributos, uso el identificador como "celda", puede dar cualquier nombre pero le di "celda" aquí. Cuando tengamos que mostrar algo o colocar algún contenido en CollectionViewCell, usaremos este identificador nombre "célula".

Busque UIimage y coloque esa imagen en CollectionViewCell y establezca todas las restricciones en cero.

No podemos simplemente crear una salida para esta UIImage en el archivo ViewController, tendremos que crear un nuevo archivo. Para crear un nuevo archivo, simplemente presione la tecla Comando  + N, haga clic en cacao toque la clase, seleccione la subclase como UICollectionViewCell, nombre el archivo como CollectionViewImageCell y haga clic en siguiente y cree un archivo, se crea un nuevo archivo.

Ahora haga clic en la celda en nuestro lado izquierdo y acceda al inspector de identidad y proporcione el nombre de la clase como nuevo archivo que creamos "ImageCollectionViewCell".

Presione el control en CollectionView y arrástrelo a nuestro ViewController y seleccione DataSource nuevamente, presione el control y arrástrelo a ViewController y seleccione Delegate. Ahora estamos listos para implementar nuestro CollectionView.

Ahora iremos al archivo ViewController y escribiremos el código allí.

import UIKit

class ViewController: UIViewController {
    var cats = [#imageLiteral(resourceName: "kate-stone-matheson-uy5t-CJuIK4-unsplash"),#imageLiteral(resourceName: "kate-stone-matheson-uy5t-CJuIK4-unsplash"),#imageLiteral(resourceName: "yoo-ho-E3LcqpQxtTU-unsplash"),#imageLiteral(resourceName: "borna-bevanda-VwqecUsYKvs-unsplash"),#imageLiteral(resourceName: "zhang-kaiyv-SlZq1f2tmaM-unsplash"),#imageLiteral(resourceName: "mikhail-vasilyev-MEb2jandkbc-unsplash"),#imageLiteral(resourceName: "mikhail-vasilyev-MEb2jandkbc-unsplash"),#imageLiteral(resourceName: "sajad-nori-s1puI2BWQzQ-unsplash"),#imageLiteral(resourceName: "tugba-fKC47FgTsVY-unsplash"),#imageLiteral(resourceName: "sajad-nori-s1puI2BWQzQ-unsplash"),#imageLiteral(resourceName: "juli-kosolapova-nAvhy44SbkA-unsplash"),#imageLiteral(resourceName: "long-ma-hxEAE88Onv0-unsplash"),#imageLiteral(resourceName: "giovanna-gomes-0cyXsESU9yw-unsplash"),#imageLiteral(resourceName: "esteban-chinchilla-9m1OFDFAuss-unsplash"),#imageLiteral(resourceName: "tugba-fKC47FgTsVY-unsplash"),#imageLiteral(resourceName: "yoo-ho-E3LcqpQxtTU-unsplash")]

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
    }
}
extension ViewController: UICollectionViewDelegate, UICollectionViewDataSource {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) - > Int {
        return cats.count
    }
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) - > UICollectionViewCell {
        let cell: ImageCollectionViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell",
            for: indexPath) as!ImageCollectionViewCell
        cell.img.image = cats[indexPath.row]
        return cell
    }
}

Rápido

Crearemos una matriz de imágenes que queremos mostrar, para esto puede colocar todas las imágenes en el archivo Assets.xcassets, aquí estamos creando una matriz de ImageLiterals y llámela cat. Recuerda que seleccionamos su Fuente de datos y Delegado, usaremos esos protocolos aquí, para esto usaremos la extensión aquí.

Extensión 

Como dice la documentación rápida, Extension agrega una nueva funcionalidad a una clase, estructura o tipo de protocolo existente. Esto incluye la capacidad de ampliar tipos para los que no tiene acceso al código fuente original. La extensión es similar a las Categorías en Swift. Extendemos UICollectionViewDelegate Protocol y UICollectionViewDataSource Protocol a nuestro ViewController.

Protocolo UICollectionViewDelegate

Se utiliza para administrar las interacciones de los usuarios en CollectionView, resaltando, seleccionando y realizando acciones en los elementos. Podemos implementar o no implementar los métodos de esta clase.

Protocolo UICollectionViewDataSource

Este protocolo utiliza el objeto DataSource para proporcionar datos a las celdas para mostrar CollectionView, al adoptar este protocolo le damos nuestros datos a la celda para mostrar elementos en CollectionView, como cuántas filas habrá en CollectionView. Al usar este protocolo, tenemos que implementar dos métodos de este protocolo. Los métodos de este protocolo no son opcionales, tenemos que implementar dos métodos necesarios de este, de lo contrario, nos dará error.

  1. NumberOfItemsInSection
    Este método devuelve un valor entero, es decir, el número de filas en CollectionView. Proporcionamos aquí la cantidad de artículos disponibles en cat array.
     
  2. CellForItemAt
    Este método devuelve una celda de CollectionView, aquí creamos una variable llamada "celda" que hereda ImageCollectionViewCell, estamos tomando esa celda por ese nombre de identificador que proporcionamos al principio, luego estamos tomando esa salida de imagen que creamos y dando imágenes a todas y cada una de las celdas de CollectionView. aquí estamos usando indexPath.row, lo que significa que en una primera celda estamos proporcionando una imagen que tenemos en nuestro primer índice en la matriz cat y estamos devolviendo esa celda a CollectionView.

Ahora ejecute la aplicación y vea el resultado en el simulador,

Entonces, en el resultado, puede ver que solo hay dos columnas disponibles y hay un espacio en blanco entre las imágenes de los gatos, no se preocupe, este artículo está escrito para ayudarlo.

Reducir espacios entre imágenes 

extension ViewController: UICollectionViewDelegateFlowLayout {
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) - > CGSize {
        let collectionWidth = collectionView.bounds.width
        return CGSize(width: collectionWidth / 3 - 2, height: collectionWidth / 3 - 2)
    }
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) - > CGFloat {
        return 2
    }
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) - > CGFloat {
        return 2
    }
}

Rápido

Usaremos UICollectionViewDelegateFlowLayout para reducir los espacios en blanco y establecer el número de columnas aquí,

UICollectionViewDelegateFlowLayout

Tiene varios métodos para trabajar, pero aquí usaremos tres métodos importantes. 

SizeForItemAt

Este método lo usamos para definir cuántas filas y columnas habrá en CollectionView, esto devuelve un marco CGSize que tiene ancho y alto. Aquí creamos una variable collectionWidth que contendrá todo el ancho de CollectionView, luego devolveremos cómo CGSize y pasaremos los parámetros ancho y alto divididos por tres. Puede dividir cualquier número dependiendo de cuántas columnas desee en su CollectionView.

Espacio entre elementos mínimo para la sección en

Este método devuelve el valor CGFloat, le damos aquí dos que puede ajustar como desee, pero recuerde una cosa, lo que estamos devolviendo aquí es que menos que el parámetro de ancho y alto en el método SizeforItemAt nos dará un aspecto perfecto.

Espaciado mínimo de línea para la sección en

Este método también devuelve CGFloat, este método es para reducir espacios entre filas en CollectionView.

Ahora ejecute la aplicación nuevamente y vea los resultados,

Así es como reducimos los espacios extra en CollectionView.

Conclusión

Reducimos los espacios entre las celdas de CollectionView. En este artículo, usamos el desplazamiento vertical de CollectionView, pero también podemos usar el desplazamiento horizontal en CollectionView. CollectionView es un tema importante en el desarrollo de iOS y también se usa en varias aplicaciones de comercio electrónico como Amazon, Flipkart, etc. Así que abra su Xcode y use este concepto en su aplicación. 

Gracias por leer este artículo, sigue aprendiendo.

Fuente: https://www.c-sharpcorner.com/article/reduce-spacing- between -collectionview-cell/

#collectionview #cell 

Reducir el espacio entre celdas de CollectionView
高橋  花子

高橋 花子

1652528649

CollectionViewセル間の間隔を狭める

iPhoneのギャラリーを開くと、画像が行と列を持つグリッドとして構造化されていることがわかります。iOS開発のCollectionViewは、その構造に似ています。グリッド形式でアイテムを表示できる機能を提供します。これはTableViewに似ていますが、CollectionViewにはアイテムを表示する機能があり、アイテムを複数の行と列に表示して水平方向にスクロールしたり、水平方向にスクロールしたりできます。垂直に。

この例では、猫の画像を含むCollectionViewがあり、これらの画像はグリッドとして構造化されており、下にスクロールできます。Apple Developer's Documentationによると、CollectionViewは、データアイテムの順序付けられたコレクションを管理し、カスタマイズ可能なレイアウトを使用してそれらを表示するオブジェクトです。この例では猫の各画像がセルに表示されるため、CollectionViewのすべてのアイテムはセルと呼ばれます。

CollectionViewは、CollectionViewのDataSourceプロパティに格納されているDataSourceというオブジェクトからデータを取得します。UICollectionViewDataSourceプロトコルを使用して、カスタムDataSourceオブジェクトを作成できます。

Xcodeから始めましょう

Xcodeを開き、シングルビューアプリケーションを作成し、プロジェクトに名前を付けて[次へ]をクリックすると、準備が整います。

main.storyboardファイルに移動してcollectionViewを検索し、CollectionViewをストーリーボードにドラッグアンドドロップして、すべての制約をゼロに設定します。ここでは、ストーリーボードに追加されたCollectionViewを確認でき、左側に追加されたCollectionViewを確認できます。ここでは、デフォルトで、CollectionViewCellタイプのUICollectionViewがCollectionViewに追加されます。このCollectionViewCellには、コンテンツビューが追加されています。これは、アイテムまたはコンテンツを保持する場所です。

次に、右側で属性インスペクター名に移動します。識別子を「セル」として使用します。任意の名前を付けることができますが、ここでは「セル」を指定しました。何かを表示したり、CollectionViewCellにコンテンツを配置したりする必要がある場合は、この識別子を使用します。名前「セル」。

UIimageを検索し、その画像をCollectionViewCellに配置して、すべての制約をゼロに設定します。

ViewControllerファイルでこのUIImageのアウトレットを単純に作成することはできません。新しいファイルを作成する必要があります。新しいファイルを作成するには、コマンド  +Nをクリックしてcocoatouch classをクリックし、サブクラスをUICollectionViewCellとして選択し、ファイルにCollectionViewImageCellという名前を付け、[次へ]をクリックしてファイルを作成すると、新しいファイルが作成されます。

次に、左側のセルをクリックしてIDインスペクターに移動し、「ImageCollectionViewCell」を作成した新しいファイルとしてクラス名を指定します。

CollectionViewのコントロールを押してViewControllerにドラッグし、もう一度DataSourceを選択します。もう一度Controlを押してViewControllerにドラッグし、Delegateを選択します。これで、CollectionViewを実装する準備が整いました。

次に、ViewControllerファイルに移動し、そこにコードを記述します。

import UIKit

class ViewController: UIViewController {
    var cats = [#imageLiteral(resourceName: "kate-stone-matheson-uy5t-CJuIK4-unsplash"),#imageLiteral(resourceName: "kate-stone-matheson-uy5t-CJuIK4-unsplash"),#imageLiteral(resourceName: "yoo-ho-E3LcqpQxtTU-unsplash"),#imageLiteral(resourceName: "borna-bevanda-VwqecUsYKvs-unsplash"),#imageLiteral(resourceName: "zhang-kaiyv-SlZq1f2tmaM-unsplash"),#imageLiteral(resourceName: "mikhail-vasilyev-MEb2jandkbc-unsplash"),#imageLiteral(resourceName: "mikhail-vasilyev-MEb2jandkbc-unsplash"),#imageLiteral(resourceName: "sajad-nori-s1puI2BWQzQ-unsplash"),#imageLiteral(resourceName: "tugba-fKC47FgTsVY-unsplash"),#imageLiteral(resourceName: "sajad-nori-s1puI2BWQzQ-unsplash"),#imageLiteral(resourceName: "juli-kosolapova-nAvhy44SbkA-unsplash"),#imageLiteral(resourceName: "long-ma-hxEAE88Onv0-unsplash"),#imageLiteral(resourceName: "giovanna-gomes-0cyXsESU9yw-unsplash"),#imageLiteral(resourceName: "esteban-chinchilla-9m1OFDFAuss-unsplash"),#imageLiteral(resourceName: "tugba-fKC47FgTsVY-unsplash"),#imageLiteral(resourceName: "yoo-ho-E3LcqpQxtTU-unsplash")]

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
    }
}
extension ViewController: UICollectionViewDelegate, UICollectionViewDataSource {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) - > Int {
        return cats.count
    }
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) - > UICollectionViewCell {
        let cell: ImageCollectionViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell",
            for: indexPath) as!ImageCollectionViewCell
        cell.img.image = cats[indexPath.row]
        return cell
    }
}

迅速

表示する画像の配列を作成します。このため、すべての画像をAssets.xcassetsファイルに配置できます。ここでは、ImageLiteralsの配列を作成し、catという名前を付けています。ここでそれらのプロトコルを使用するデータソースとデリゲートを選択したことを覚えています。このために、ここで拡張機能を使用します。

拡大 

迅速なドキュメントにあるように、Extensionは既存のクラス、構造、またはプロトコルタイプに新しい機能を追加します。これには、元のソースコードにアクセスできないタイプを拡張する機能が含まれます。拡張機能は、swiftのCategoriesに似ています。UICollectionViewDelegateプロトコルとUICollectionViewDataSourceプロトコルをViewControllerに拡張します。

UICollectionViewDelegateプロトコル

これは、CollectionViewでのユーザー操作の管理、アイテムの強調表示、選択、およびアクションの実行に使用されます。このクラスのメソッドを実装する場合としない場合があります。

UICollectionViewDataSourceプロトコル

このプロトコルは、DataSourceオブジェクトを使用して、CollectionViewを表示するセルにデータを提供します。このプロトコルを採用することにより、CollectionViewの行数など、CollectionViewの表示アイテムのデータをセルに提供します。このプロトコルを使用することにより、このプロトコルの2つの方法を実装する必要があります。このプロトコルのメソッドはオプションではありません。これには2つの必要なメソッドを実装する必要があります。そうしないと、エラーが発生します。

  1. NumberOfItemsInSection
    このメソッドは整数値、つまりCollectionViewの行数を返します。ここでは、猫の配列で利用可能なアイテムの数を提供しました。
     
  2. CellForItemAt
    このメソッドは、CollectionViewのセルを返します。ここでは、ImageCollectionViewCellを継承する「cell」という変数を作成しました。最初に指定した識別子名でそのセルを取得し、作成した画像アウトレットを取得して画像を提供します。 CollectionViewのすべてのセルに。ここではindexPath.rowを使用しています。これは、最初のセルで、cat配列の最初のインデックスにある画像を提供し、そのセルをCollectionViewに返すことを意味します。

次に、アプリを実行して、シミュレーターで結果を確認します。

したがって、結果として、使用可能な列は2つだけであり、猫の画像の間に空白があることがわかります。この記事が役立つように書かれていることを心配しないでください。

画像間のスペースを減らす 

extension ViewController: UICollectionViewDelegateFlowLayout {
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) - > CGSize {
        let collectionWidth = collectionView.bounds.width
        return CGSize(width: collectionWidth / 3 - 2, height: collectionWidth / 3 - 2)
    }
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) - > CGFloat {
        return 2
    }
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) - > CGFloat {
        return 2
    }
}

迅速

ここでは、UICollectionViewDelegateFlowLayoutを使用して空白を減らし、列数を設定します。

UICollectionViewDelegateFlowLayout

作業する方法はいくつかありますが、ここでは3つの重要な方法を使用します。 

SizeForItemAt

CollectionViewに含まれる行と列の数を定義するために使用するこのメソッドは、幅と高さを持つフレームCGSizeを返します。ここでは、CollectionViewの全幅を含むcollectionWidth変数を作成し、CGSizeとパスパラメーターのwidthとheightを3で割った値を返します。これにより、CollectionViewに必要な列数に応じて任意の数を除算できます。

MinimumInteritemSpacingForSectionAt

このメソッドはCGFloat値を返します。ここでは、必要に応じて調整できる2つを提供していますが、ここで返されるものの1つから、SizeforItemAtメソッドのwidthおよびheightパラメーターから差し引いたものを覚えておいてください。

MinimumLineSpacingForSectionAt

このメソッドはCGFloatも返します。このメソッドは、CollectionViewの行間のスペースを減らすためのものです。

アプリをもう一度実行して結果を確認します。

これが、CollectionViewの余分なスペースを減らす方法です。

結論

CollectionViewセル間のスペースを減らします。この記事では、縦スクロールのCollectionViewを使用しましたが、CollectionViewで横スクロールを使用することもできます。CollectionViewはiOS開発の重要なトピックであり、Amazon、Flipkartなどのいくつかのeコマースアプリケーションでも使用されます。Xcodeを開いて、この概念をアプリケーションで使用してください。 

この記事を読んでくれてありがとう-学び続けてください。

ソース:https ://www.c-sharpcorner.com/article/reduce-spacing-between-collectionview-cell/

#collectionview #cell 

CollectionViewセル間の間隔を狭める
Rowena  Cox

Rowena Cox

1625863800

Using Xamarin.Forms SwipeView + CollectionView Bonus!

Since touchscreens the swipe gesture is suddenly a thing! Luckily Xamarin.Forms now has the SwipeView. With SwipeView you can swipe basically any visual element on screen. There is lots of events and properties to customize the whole experience to your needs.

In this video we will see how to use SwipeView and how to apply it to a CollectionView.

🔗 Links
Sample code: https://github.com/jfversluis/XFSwipeViewSample
DataTemplate Video: https://www.youtube.com/watch?v=O0Ym-x8joqg
Data Binding Playlist: https://www.youtube.com/watch?v=Or_qn8i8jVM&list=PLfbOp004UaYWOuVUuEtGlpkDIC1houhn_

Xamarin Forms Repo: https://github.com/xamarin/Xamarin.Forms
Xamarin.Forms SwipeView Docs: https://docs.microsoft.com/xamarin/xamarin-forms/user-interface/swipeview

⏱ Timestamps
0:00 Intro
0:22 Sample App Outline
1:00 Start Implementing SwipeView
1:45 Explore SwipeView APIs
2:35 Implement SwipeItem
4:40 Customize SwipeItem Behavior
9:20 Programatically Open and Close SwipeItems
9:50 SwipeView IsEnabled
10:10 Using SwipeView with CollectionView
15:10 Outro

#listview #swipeview #xamarinforms #collectionview

Using Xamarin.Forms SwipeView + CollectionView Bonus!

Scroll to any Item in Your Xamarin.forms CollectionView From Your ViewModel

In this post, I am going to show you how we can easily extend CollectionView to implement ScrollTo-functionality through DataBinding from a ViewModel (for both grouped and non-grouped data sources).

If you are working with collections in your app, chances are high you are going to want (or need) to scroll to a specific item at some point. CollectionView has the ScrollTo method that allows you to do so. If you are using MVVM in your app however, there is no built-in support to call this method.

My solution

My solution for this challenge consists of following parts:

  • BindableProperty in an extended CollectionView class to bind the item we want to scroll to
  • a configuration class to control the scrolling behavior
  • a base interface with the configuration and two variants derived from it (one for ungrouped items, one for grouped ones)

Let’s have a look at the ScrollConfiguration class:

public class ScrollToConfiguration { public bool Animated { get ; set ; } = true ; public ScrollToPosition ScrollToPosition { get ; set ; } = ScrollToPosition. Center ; }

These two properties are used to tell our extended CollectionView how the scrolling to the item will behave. The above default values are my preferred ones, feel free to change them in your implementation.

#xamarin #binding #collectionview #github

Scroll to any Item in Your Xamarin.forms CollectionView From Your ViewModel
Paolo  Hudson

Paolo Hudson

1589716800

Xamarin.Forms 101: Intro to CollectionView and RefreshView

Let’s take a step back in a new mini-series that I like to call Xamarin.Forms 101. In each episode we will walk through a basic building block of Xamarin.Forms to help you build awesome cross-platform iOS, Android, and Windows applications in .NET. This week we take a look at how to show lists of data, and how to make an entire view refresh.

Youtube channel: Xamarin Developers - https://www.youtube.com/watch?v=JY900hOQCKQ

#xamarin #collectionview #refreshview #xamarinforms

Xamarin.Forms 101: Intro to CollectionView and RefreshView