我希望我的细胞像这样显示
X
Group 1
X X X
X X
Group 2
X X X
X X X
但是,这是我得到的输出。我不期望名为Home的单元格在中心对齐,也不期望第二行Employee通信中间的空间。
private class MenuDelegate : UICollectionViewDelegateFlowLayout
{
private const int interItemSpacing = 12;
private readonly double _itemWidth;
private readonly double _itemsPerRow;
private readonly List<MenuItem> _items;
public MenuDelegate(List<MenuItem> items)
{
_items = items;
_itemsPerRow = DisplayUtils.IsIPad ? 5 : 3;
_itemWidth = (PlatformConstants.MenuWidth - ((_itemsPerRow - 1) * interItemSpacing)) / _itemsPerRow;
}
public override CGSize GetSizeForItem(UICollectionView collectionView,
UICollectionViewLayout layout, NSIndexPath indexPath)
{
if (_items[indexPath.Row].Parent) {
return new CGSize(DisplayUtils.ScreenWidth, 44);
}
return new CGSize(_itemWidth, _itemWidth);
}
public override void ItemSelected(UICollectionView collectionView, NSIndexPath indexPath)
{
HandleCellSelect(_items[indexPath.Row]);
}
public override nfloat GetMinimumInteritemSpacingForSection(UICollectionView collectionView, UICollectionViewLayout layout, nint section)
{
return interItemSpacing;
}
public override nfloat GetMinimumLineSpacingForSection(UICollectionView collectionView, UICollectionViewLayout layout, nint section)
{
return float.Epsilon;
}
}
您是否尝试在自定义LayoutAttributesForElementsInRect
中重写UICollectionViewFlowLayout
并设置属性。这发生在UICollectionViewFlowLayout为单个单元格返回2个属性时。
public class CustomFlowLayout : UICollectionViewFlowLayout
{
public override UICollectionViewLayoutAttributes[] LayoutAttributesForElementsInRect(CGRect rect)
{
UICollectionViewLayoutAttributes[] attributes = base.LayoutAttributesForElementsInRect(rect);
UICollectionViewLayoutAttributes[] newAttributes = new UICollectionViewLayoutAttributes[attributes.Length];
foreach (UICollectionViewLayoutAttributes attribute in attributes)
{
if ((attribute.Frame.X + attribute.Frame.Width<= this.CollectionViewContentSize.Width) &&
(attribute.Frame.Y + attribute.Frame.Height <= this.CollectionViewContentSize.Height))
{
newAttributes.Append(attribute);
}
}
return newAttributes;
}
}
有关详细信息,请查看here
我有一个子类UICollectionViewFlowLayout来实现所需的结果。
private class CustomFlowLayout : UICollectionViewFlowLayout
{
public override UICollectionViewLayoutAttributes[] LayoutAttributesForElementsInRect(CGRect rect)
{
var attributes = base.LayoutAttributesForElementsInRect(rect);
var leftMargin = SectionInset.Left;
var maxY = 2.0f;
var horizontalSpacing = 6f; // spacing between the items.
foreach (var attribute in attributes) {
if (attribute.Frame.Y >= maxY || attribute.Frame.X == SectionInset.Left) {
leftMargin = SectionInset.Left;
}
if (attribute.Frame.X == SectionInset.Left)
leftMargin = SectionInset.Left;
else
attribute.Frame = new CGRect(leftMargin, attribute.Frame.Y, attribute.Frame.Width, attribute.Frame.Height);
leftMargin += attribute.Frame.Width + horizontalSpacing;
maxY = (float)Math.Max(attribute.Frame.GetMaxY(), maxY);
}
return attributes;
}
}