我正在使用多种尺寸的标签创建集合视图。这些标签都具有相同的高度,但它们的宽度会动态更改。
这是我的集合视图布局的代码:
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 :(得分:0)
当您使用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;
}
它的工作原理如下: