Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/318.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何使用UICollectionViewCompositionLayout和多种单元格类型创建自动调整大小的单元格?_C#_Swift_Xamarin.ios_Ios13_Autosize - Fatal编程技术网

C# 如何使用UICollectionViewCompositionLayout和多种单元格类型创建自动调整大小的单元格?

C# 如何使用UICollectionViewCompositionLayout和多种单元格类型创建自动调整大小的单元格?,c#,swift,xamarin.ios,ios13,autosize,C#,Swift,Xamarin.ios,Ios13,Autosize,我试图在iOS13上使用新的UICollectionViewCompositionalLayout。我想显示两种不同的单元格类型,但我想让布局系统自动调整单元格大小。我想利用NSCollectionLayoutDimension。估计认为自动大小将由我负责 我正试图用Xamarin来实现这一点,但是Swift程序员应该能够很好地阅读下面的代码。我对自动布局和动态单元格大小不是很在行,但到目前为止,我已经能够查看在线资源了。几乎每个UICollectionViewCompositionalLayo

我试图在iOS13上使用新的
UICollectionViewCompositionalLayout
。我想显示两种不同的单元格类型,但我想让布局系统自动调整单元格大小。我想利用
NSCollectionLayoutDimension。估计
认为自动大小将由我负责

我正试图用Xamarin来实现这一点,但是Swift程序员应该能够很好地阅读下面的代码。我对自动布局和动态单元格大小不是很在行,但到目前为止,我已经能够查看在线资源了。几乎每个
UICollectionViewCompositionalLayout
示例似乎都在使用单个单元格模板

public class MyViewController : UIViewController
{
    private UICollectionView _collectionView;

    public static List<BaseModel> Models = new List<BaseModel>();

    public override void ViewDidLoad()
    {
        base.ViewDidLoad();

        PopulateModels();

        _collectionView = new UICollectionView(View.Frame, GetUiCollectionViewLayout())
        {
            BackgroundColor = UIColor.Brown,
            DataSource = new MyViewUICollectionViewDataSource(),
            ContentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentBehavior.Never,
            TranslatesAutoresizingMaskIntoConstraints = false,
            ShowsVerticalScrollIndicator = false,
            ShowsHorizontalScrollIndicator = false
        };

        _collectionView.RegisterClassForCell(typeof(MyViewUICollectionViewCell), MyViewUICollectionViewCell.ReuseIdentifier);
        _collectionView.RegisterClassForCell(typeof(MyViewUICollectionViewCell2), MyViewUICollectionViewCell2.ReuseIdentifier);

        View.AddSubview(_collectionView);

        NSLayoutConstraint.ActivateConstraints(new[]
        {
            _collectionView.TopAnchor.ConstraintEqualTo(View.SafeAreaLayoutGuide.TopAnchor),
            _collectionView.BottomAnchor.ConstraintEqualTo(View.SafeAreaLayoutGuide.BottomAnchor),
            _collectionView.LeftAnchor.ConstraintEqualTo(View.SafeAreaLayoutGuide.LeftAnchor),
            _collectionView.RightAnchor.ConstraintEqualTo(View.SafeAreaLayoutGuide.RightAnchor)
        });
    }

    private static void PopulateModels()
    {
        for (var i = 0; i < 100; i++)
        {
            BaseModel baseModel;

            if (i % 2 == 0)
            {
                baseModel = new Model1
                {
                    UIColor = UIColor.Red
                };
            }
            else
            {
                baseModel = new Model2
                {
                    Text = "Item " + i
                };
            }

            Models.Add(baseModel);
        }
    }

    private UICollectionViewLayout GetUiCollectionViewLayout()
    {
        var layoutSize = NSCollectionLayoutSize.Create(NSCollectionLayoutDimension.CreateFractionalWidth(1), NSCollectionLayoutDimension.CreateEstimated(200));
        var item = NSCollectionLayoutItem.Create(layoutSize);
        var group = NSCollectionLayoutGroup.CreateHorizontal(layoutSize: layoutSize, subitem: item, count: 1);
        var section = NSCollectionLayoutSection.Create(group);

        // this is what you need for content inset
        section.ContentInsets = new NSDirectionalEdgeInsets(top: 5, leading: 5, bottom: 5, trailing: 5);

        // this is spacing between items
        section.InterGroupSpacing = 5;

        var layout = new UICollectionViewCompositionalLayout(section);

        return layout;
    }
}

public class BaseModel
{

}

public class Model1 : BaseModel
{
    public UIColor UIColor { get; set; }
}

public class Model2 : BaseModel
{
    public string Text { get; set; }
}

public class MyViewUICollectionViewDataSource : UICollectionViewDataSource
{
    public override UICollectionViewCell GetCell(UICollectionView collectionView, NSIndexPath indexPath)
    {
        var model = MyViewController.Models[(int) indexPath.Item];

        switch (model)
        {
            case Model1 model1:
            {
                var cell = collectionView.DequeueReusableCell(MyViewUICollectionViewCell.ReuseIdentifier, indexPath) as MyViewUICollectionViewCell;
                cell.ColorView.BackgroundColor = model1.UIColor;
                return cell;
            }
            case Model2 model2:
            {
                var cell2 = collectionView.DequeueReusableCell(MyViewUICollectionViewCell2.ReuseIdentifier, indexPath) as MyViewUICollectionViewCell2;
                cell2.Label.Text = model2.Text;
                return cell2;
            }
            default:
                throw new Exception();
        }
    }

    public override nint GetItemsCount(UICollectionView collectionView, nint section)
    {
        return MyViewController.Models.Count;
    }
}

public class MyViewUICollectionViewCell : UICollectionViewCell
{
    public const string ReuseIdentifier = "MyViewUICollectionViewCell";

    public UIView ColorView { get; }

    [Export("initWithFrame:")]
    public MyViewUICollectionViewCell(CGRect frame) : base(frame)
    {
        var container = new UIView
        {
            BackgroundColor = UIColor.White,
            TranslatesAutoresizingMaskIntoConstraints = false
        };

        container.Layer.CornerRadius = 5;

        ContentView.AddSubview(container);

        container.TopAnchor.ConstraintEqualTo(ContentView.TopAnchor).Active = true;
        container.LeftAnchor.ConstraintEqualTo(ContentView.LeftAnchor).Active = true;
        container.BottomAnchor.ConstraintEqualTo(ContentView.BottomAnchor).Active = true;
        container.RightAnchor.ConstraintEqualTo(ContentView.RightAnchor).Active = true;

        ColorView = new UIView
        {
            TranslatesAutoresizingMaskIntoConstraints = false
        };

        ColorView.Layer.CornerRadius = 10;

        container.AddSubview(ColorView);

        ColorView.CenterXAnchor.ConstraintEqualTo(container.CenterXAnchor).Active = true;
        ColorView.CenterYAnchor.ConstraintEqualTo(container.CenterYAnchor).Active = true;
        ColorView.WidthAnchor.ConstraintEqualTo(20).Active = true;
        ColorView.HeightAnchor.ConstraintEqualTo(50).Active = true;
    }
}

public class MyViewUICollectionViewCell2 : UICollectionViewCell
{
    public const string ReuseIdentifier = "MyViewUICollectionViewCell2";

    public UILabel Label { get; }

    [Export("initWithFrame:")]
    public MyViewUICollectionViewCell2(CGRect frame) : base(frame)
    {
        var container = new UIView
        {
            BackgroundColor = UIColor.White,
            TranslatesAutoresizingMaskIntoConstraints = false
        };

        container.Layer.CornerRadius = 5;

        ContentView.AddSubview(container);

        container.TopAnchor.ConstraintEqualTo(ContentView.TopAnchor).Active = true;
        container.LeftAnchor.ConstraintEqualTo(ContentView.LeftAnchor).Active = true;
        container.BottomAnchor.ConstraintEqualTo(ContentView.BottomAnchor).Active = true;
        container.RightAnchor.ConstraintEqualTo(ContentView.RightAnchor).Active = true;

        Label = new UILabel
        {
            TranslatesAutoresizingMaskIntoConstraints = false
        };

        container.AddSubview(Label);

        Label.CenterXAnchor.ConstraintEqualTo(container.CenterXAnchor).Active = true;
        Label.CenterYAnchor.ConstraintEqualTo(container.CenterYAnchor).Active = true;
        //Label.WidthAnchor.ConstraintEqualTo(20).Active = true;
        //Label.HeightAnchor.ConstraintEqualTo(20).Active = true;
    }
}
公共类MyViewController:UIViewController
{
私有UICollectionView collectionView;
公共静态列表模型=新列表();
公共覆盖无效ViewDidLoad()
{
base.ViewDidLoad();
PopulateModels();
_collectionView=新建UICollectionView(View.Frame,GetUiCollectionViewLayout())
{
BackgroundColor=UIColor.Brown,
DataSource=新建MyViewUICollectionViewDataSource(),
ContentInsetAdjustmentBehavior=UIScrollViewContentInsetAdjustmentBehavior.Never,
TranslatesAutoresizingMaskIntoConstraints=false,
ShowsVerticalScrollIndicator=false,
showshorizontalscrolindicator=false
};
_RegisterClassForCell(typeof(MyViewUICollectionViewCell)、MyViewUICollectionViewCell.ReuseIdentifier);
_RegisterClassForCell(typeof(MyViewUICollectionViewCell2)、MyViewUICollectionViewCell2.ReuseIdentifier);
View.AddSubview(_collectionView);
NSLayoutConstraint.ActivateConstraint(新[]
{
_collectionView.TopAnchor.ConstraintEqualTo(View.SafeArealLayoutGuide.TopAnchor),
_collectionView.BottomAnchor.ConstraintEqualTo(View.SafeArealLayoutGuide.BottomAnchor),
_collectionView.LeftAnchor.ConstraintEqualTo(View.SafeAreaLayoutGuide.LeftAnchor),
_collectionView.RightAnchor.ConstraintEqualTo(View.SafeArealLayoutGuide.RightAnchor)
});
}
私有静态void PopulateModels()
{
对于(变量i=0;i<100;i++)
{
BaseModel BaseModel;
如果(i%2==0)
{
baseModel=新模型1
{
UIColor=UIColor.Red
};
}
其他的
{
baseModel=新模型2
{
Text=“项目”+i
};
}
Models.Add(baseModel);
}
}
专用UICollectionViewLayout GetUiCollectionViewLayout()
{
var layoutSize=NSCollectionLayoutSize.Create(nscollectionlayoutdimmension.Create分馏宽度(1),nscollectionlayoutdimmension.CreateEstimated(200));
var item=NSCollectionLayoutItem.Create(layoutSize);
var group=NSCollectionLayoutGroup.CreateHorizontal(layoutSize:layoutSize,子项:项,计数:1);
var section=NSCollectionLayoutSection.Create(组);
//这就是内容插入所需的内容
section.ContentInsets=新的NSDirectionalEdgeInsets(顶部:5,前导:5,底部:5,尾随:5);
//这是项目之间的间距
section.InterGroupSpacing=5;
var布局=新UICollectionViewCompositionLayout(截面);
返回布局;
}
}
公共类基模型
{
}
公共类Model1:BaseModel
{
公共UIColor UIColor{get;set;}
}
公共类Model2:BaseModel
{
公共字符串文本{get;set;}
}
公共类MyViewUICollectionViewDataSource:UICollectionViewDataSource
{
公共覆盖UICollectionViewCell GetCell(UICollectionView collectionView,NSIndexPath indexPath)
{
var model=MyViewController.Models[(int)indexPath.Item];
交换机(型号)
{
案例模型1模型1:
{
var cell=collectionView.DequeueReusableCell(MyViewUICollectionViewCell.ReuseIdentifier,indexPath)作为MyViewUICollectionViewCell;
cell.ColorView.BackgroundColor=model1.UIColor;
返回单元;
}
案例模式2模式2:
{
var cell2=collectionView.DequeueReusableCell(MyViewUICollectionViewCell2.ReuseIdentifier,indexPath)作为MyViewUICollectionViewCell2;
cell2.Label.Text=model2.Text;
返回单元格2;
}
违约:
抛出新异常();
}
}
公共覆盖nint GetItemsCount(UICollectionView collectionView,nint部分)
{
返回MyViewController.Models.Count;
}
}
公共类MyViewUICollectionViewCell:UICollectionViewCell
{
public const string ReuseIdentifier=“MyViewUICollectionViewCell”;
公共UIView颜色视图{get;}
[导出(“initWithFrame:”)]
公共MyViewUICollectionViewCell(CGRect帧):基础(帧)
{
var容器=新UIView
{
BackgroundColor=UIColor.White,
TranslatesAutoresizingMaskIntoConstraints=false
};
container.Layer.CornerRadius=5;
AddSubview(容器);
container.TopAnchor.ConstraintEqualTo(ContentView.TopAnchor).Active=true;
container.LeftAnchor.ConstraintEqualTo(ContentView.LeftAnchor).Active=true;
container.BottomAnchor.ConstraintEqualTo(ContentView.BottomAnchor).Active=true;
container.RightAnchor.ConstraintEqualTo(ContentView.RightAnchor).Active=true;
ColorView=新UIView
{
TranslatesAutoresizingMaskIntoConstraints=false
};
ColorView.Layer.CornerRadius=10;
container.AddSubview(ColorView);
ColorView.CenterXAnchor.ConstraintEqualTo(container.CenterXAnchor.Active=tr
public class MyViewUICollectionViewCell2 : UICollectionViewCell
{
    public const string ReuseIdentifier = "MyViewUICollectionViewCell2";

    public UILabel Label { get; }

    [Export("initWithFrame:")]
    public MyViewUICollectionViewCell2(CGRect frame) : base(frame)
    {
        var container = new UIView
        {
            BackgroundColor = UIColor.White,
            TranslatesAutoresizingMaskIntoConstraints = false
        };

        container.Layer.CornerRadius = 5;

        ContentView.AddSubview(container);

        container.TopAnchor.ConstraintEqualTo(ContentView.TopAnchor).Active = true;
        container.LeftAnchor.ConstraintEqualTo(ContentView.LeftAnchor).Active = true;
        container.BottomAnchor.ConstraintEqualTo(ContentView.BottomAnchor).Active = true;
        container.RightAnchor.ConstraintEqualTo(ContentView.RightAnchor).Active = true;

        Label = new UILabel
        {
            Lines = 0;
            TranslatesAutoresizingMaskIntoConstraints = false
        };

        container.AddSubview(Label);

        Label.TopAnchor.ConstraintEqualTo(container.TopAnchor).Active = true;
        Label.LeftAnchor.ConstraintEqualTo(container.LeftAnchor).Active = true;
        Label.BottomAnchor.ConstraintEqualTo(container.BottomAnchor).Active = true;
        Label.RightAnchor.ConstraintEqualTo(container.RightAnchor).Active = true;

        //Label.CenterXAnchor.ConstraintEqualTo(container.CenterXAnchor).Active = true;
        //CenterYAnchor.ConstraintEqualTo(container.CenterYAnchor).Active = true;
        //Label.WidthAnchor.ConstraintEqualTo(20).Active = true;
        //Label.HeightAnchor.ConstraintEqualTo(20).Active = true;
    }
}