左对齐UICollectionView单元格当它在Xamarin.ios中有一个项目

左对齐UICollectionView单元格当它在Xamarin.ios中有一个项目

问题描述:

我正在创建具有多个标签大小的集合视图。这些标签都具有相同的高度,但宽度会动态变化。左对齐UICollectionView单元格当它在Xamarin.ios中有一个项目

这是我收集视图布局的代码:

EstimatedItemSize = new CGSize(50f, 35f); 

MinimumInteritemSpacing = 10f; 

MinimumLineSpacing = 10f; 

public override UICollectionViewLayoutAttributes[] LayoutAttributesForElementsInRect(CGRect rect) 
{ 
var attributes = base.LayoutAttributesForElementsInRect(rect); 

     for (var i = 1; i < attributes.Length; ++i) 
     { 
      var currentLayoutAttributes = attributes[i]; 
      var previousLayoutAttributes = attributes[i - 1]; 
      var maximumSpacing = MinimumInteritemSpacing; 
      var previousLayoutEndPoint = previousLayoutAttributes.Frame.Right; 
      if (previousLayoutEndPoint + maximumSpacing + currentLayoutAttributes.Frame.Size.Width >= CollectionViewContentSize.Width) 
      { 
       continue; 
      } 
      var frame = currentLayoutAttributes.Frame; 
      frame.X = previousLayoutEndPoint + maximumSpacing; 
      currentLayoutAttributes.Frame = frame; 
     } 
     return attributes; 
    } 

我的问题是:当我有我的集合中的一个项目来查看它的显示在屏幕*,并LayoutAttributesForElementsInRect方法不会被调用。但我需要在左侧显示它。

如果我将EstimatedItemSize = new CGSize(50f, 35f)更改为ItemSize = new CGSize(50f, 35f)它会正确显示,但宽度不会动态更改。

+0

我有发表答复。或者你可以使用一些其他的第三方库:https://github.com/mokagio/UICollectionViewLeftAlignedLayout。 –

您可以添加一些代码来改变第一小区的位置,当您使用EstimatedItemSize,就像这样:

 public override UICollectionViewLayoutAttributes[] LayoutAttributesForElementsInRect(CoreGraphics.CGRect rect) 
     { 

      var attributes = base.LayoutAttributesForElementsInRect(rect); 


      //Add these lines to change the first cell's position of the collection view. 
      var firstCellFrame = attributes[0].Frame; 
      firstCellFrame.X = 0; 
      attributes[0].Frame = firstCellFrame; 


      for (var i = 1; i < attributes.Length; ++i) 
      { 
       var currentLayoutAttributes = attributes[i]; 
       var previousLayoutAttributes = attributes[i - 1]; 
       var maximumSpacing = MinimumInteritemSpacing; 
       var previousLayoutEndPoint = previousLayoutAttributes.Frame.Right; 
       if (previousLayoutEndPoint + maximumSpacing + currentLayoutAttributes.Frame.Size.Width >= CollectionViewContentSize.Width) 
       { 
        continue; 
       } 
       var frame = currentLayoutAttributes.Frame; 
       frame.X = previousLayoutEndPoint + maximumSpacing; 
       currentLayoutAttributes.Frame = frame; 
      } 
      return attributes; 
     } 

它工作正常,像这样:

enter image description here