Peter
Peter

Reputation: 71

iOS custom collection view cell in Xamarin

I am trying to use Xamarin.iOS. Everything makes sense until I get to customizing UI. How would you create a collection with customized look and feel for the collection control and it's cell controls?

Upvotes: 0

Views: 5644

Answers (2)

Ben Bishop
Ben Bishop

Reputation: 1414

UICollectionView is a bit similar to UITableView. To get the customization you want, you first need to define your custom cell class:

public class AnimalCell : UICollectionViewCell
{
        UIImageView imageView;

        [Export ("initWithFrame:")]
        public AnimalCell (System.Drawing.RectangleF frame) : base (frame)
        {
                BackgroundView = new UIView{BackgroundColor = UIColor.Orange};

                SelectedBackgroundView = new UIView{BackgroundColor = UIColor.Green};

                ContentView.Layer.BorderColor = UIColor.LightGray.CGColor;
                ContentView.Layer.BorderWidth = 2.0f;
                ContentView.BackgroundColor = UIColor.White;
                ContentView.Transform = CGAffineTransform.MakeScale (0.8f, 0.8f);

                imageView = new UIImageView (UIImage.FromBundle ("placeholder.png"));
                imageView.Center = ContentView.Center;
                imageView.Transform = CGAffineTransform.MakeScale (0.7f, 0.7f);

                ContentView.AddSubview (imageView);
        }

        public UIImage Image {
                set {
                        imageView.Image = value;
                }
        }
}

Then you can reference this cell in your UICollectionViewDataSource class by overriding the GetCell method:

public override UICollectionViewCell GetCell (UICollectionView collectionView, MonoTouch.Foundation.NSIndexPath indexPath)
{
        var animalCell = (AnimalCell)collectionView.DequeueReusableCell (animalCellId, indexPath);

        var animal = animals [indexPath.Row];

        animalCell.Image = animal.Image;

        return animalCell;
}

For more info, you should checkout this tutorial on Xamarin's website that I pulled these examples from: http://docs.xamarin.com/guides/ios/user_interface/introduction_to_collection_views

Upvotes: 4

Jason
Jason

Reputation: 89102

to add a background image, try this (in ViewDidLoad)

myview.BackgroundColor = UIColor.FromPatternImage(UIImage.FromFile("myimage.png"));

Upvotes: 0

Related Questions