Skip to content

Instantly share code, notes, and snippets.

@aloisdeniel
Created June 20, 2017 14:37
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save aloisdeniel/eed4093a1fee22fc0f04760aaa51201e to your computer and use it in GitHub Desktop.
Save aloisdeniel/eed4093a1fee22fc0f04760aaa51201e to your computer and use it in GitHub Desktop.
Snapped Horizontal UICollectionView in Xamarin.iOS
namespace SnapCollection
{
using UIKit;
using CoreGraphics;
public class SnapLayout : UICollectionViewFlowLayout
{
public SnapLayout()
{
this.ItemSize = new CGSize(300, 250);
this.ScrollDirection = UICollectionViewScrollDirection.Horizontal;
}
CGPoint mostRecentOffset = new CGPoint();
public override CGPoint TargetContentOffset(CGPoint proposedContentOffset, CGPoint scrollingVelocity)
{
if(scrollingVelocity.X == 0)
{
return mostRecentOffset;
}
var cv = this.CollectionView;
if(cv != null)
{
var cvBounds = this.CollectionView.Bounds;
var halfWidth = cvBounds.Size.Width * 0.5f;
var attributesForVisibleCells = this.LayoutAttributesForElementsInRect(cvBounds);
if(attributesForVisibleCells != null)
{
if (proposedContentOffset.X == -(cv.ContentInset.Left))
{
return proposedContentOffset;
}
UICollectionViewLayoutAttributes candidateAttributes = null;
foreach (var attributes in attributesForVisibleCells)
{
if (attributes.RepresentedElementCategory != UICollectionElementCategory.Cell)
{
continue;
}
if ((attributes.Center.X == 0) || (attributes.Center.X > (cv.ContentOffset.X + halfWidth) && scrollingVelocity.X < 0)) {
continue;
}
candidateAttributes = attributes;
}
if(candidateAttributes == null)
{
return mostRecentOffset;
}
return mostRecentOffset = new CGPoint(candidateAttributes.Center.X - halfWidth, proposedContentOffset.Y);
}
}
return mostRecentOffset = base.TargetContentOffset(proposedContentOffset, scrollingVelocity);
}
}
}
namespace SnapCollection
{
using System;
using UIKit;
public partial class ViewController : UIViewController
{
protected ViewController(IntPtr handle) : base(handle) { }
public override void ViewDidLoad()
{
base.ViewDidLoad();
this.collectionView.CollectionViewLayout = new SnapLayout();
this.collectionView.Source = new Source();
this.collectionView.DecelerationRate = UIScrollView.DecelerationRateFast;
var insets = this.collectionView.ContentInset;
insets.Left = 10;
insets.Right = 10;
this.collectionView.ContentInset = insets;
}
}
}
@aloisdeniel
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment