1.创建初始化
private UICollectionView collectionView;
private UICollectionViewFlowLayout collectionViewLayout;
private List<UIImage> collectionData;
2.设置行间距和网格大小
private void uiConfig()
{
//设置假的数据源数组
collectionData = new List<UIImage>();
for (int i = 0; i < 50; i++)
{
collectionData.Add(UIImage.FromFile("WechatIMG3"));
}
//初始化UICollectionView
collectionViewLayout = new UICollectionViewFlowLayout();
collectionViewLayout.MinimumLineSpacing = 20f;//设置行距
collectionViewLayout.MinimumInteritemSpacing = 10f;//设置列距
collectionViewLayout.SectionInset = new UIEdgeInsets(20, 20, 20, 20);//设置边界
collectionViewLayout.ItemSize = new CoreGraphics.CGSize(70f, 70f);//设置网格大小
collectionView = new UICollectionView(this.View.Bounds, collectionViewLayout);
collectionView.BackgroundColor = UIColor.LightTextColor;
collectionView.RegisterNibForCell(ImageCell.Nib, "ImageCell");
collectionView.Source = new collectionSource(this);
this.View.AddSubview(collectionView);
}
3.代理方法
private class collectionSource : UICollectionViewSource
{
ViewController owner;
public collectionSource(ViewController owner)
{
this.owner = owner;
}
//设置网格个数
public override nint GetItemsCount(UICollectionView collectionView, nint section)
{
return owner.collectionData.Count;
}
//设置网格中的内容
public override UICollectionViewCell GetCell(UICollectionView collectionView, NSIndexPath indexPath)
{
ImageCell cell = (ImageCell)collectionView.DequeueReusableCell((NSString)ImageCell.Key, indexPath);
cell.myImageView.Image = owner.collectionData[indexPath.Row];
return cell;
}
//选中某一个网格
public override void ItemSelected(UICollectionView collectionView, NSIndexPath indexPath)
{
UIAlertView alert = new UIAlertView();
alert.Title = string.Format("你选择了第{0}个网格", indexPath.Row);
alert.AddButton("确定");
alert.Show();
}
}
4.运行效果