title: How have a custom UICollectionViewCell fill horizontal width?
body: <p>I'm trying to make an app for people of my student dancing association to find a dance partner. It's been a fun project during corona. Everything is done in ASP Core 5 and Xamarin Forms, and it's almost ready for testing. However, I'm having some trouble with the chat UI. When I use a CollectionView in Forms, it loads very slowly, due to rendering performance (at least on Android, iOS is generally much faster). To solve that I tried creating it as a view and use native renderers for iOS and Android. With Android, I simply used a NuGet package (XamarinLibrary.Xamarin.AndroidX.ChatKit), but for iOS I could find no such package. There's a native SwiftUI package (MessageKit), though I don't know how to wrap that (and the documentation is a lot). So I started to instead write it in Xamarin iOS. My test loads really quickly, although I'm now struggling with the layout of the Collection and the ViewCell. Could someone show me how to create message cells that fill the horizontal space?</p>
  <p>Thanks in advance! :)</p>
  <p>This is what it looks like right now:</p>
  <p><a href="https://i.stack.imgur.com/s0uou.png" rel="nofollow noreferrer">Screenshot</a></p>
  <p>[UPDATE] I partially solved the issue by adding this (though it does not work in the constructor):</p>
  <p><a href="https://i.stack.imgur.com/ZDCDg.png" rel="nofollow noreferrer">Screenshot 2</a></p>
  <pre><code>public override bool ShouldInvalidateLayoutForBoundsChange(CGRect newBounds) {
      MinimumLineSpacing = 10;
      MinimumInteritemSpacing = 10;
      SectionInset = new UIEdgeInsets(top: 0, left: 10, bottom: 0, right: 10);
      ItemSize = new CGSize(width: (newBounds.Width - 20), height: 100);
  
      return true;
  }
  </code></pre>
  <p>My code currently (the data source isn't correct yet):</p>
  <pre><code>    public class MessageListLayout : UICollectionViewFlowLayout {
  
          public MessageListLayout() {
              ItemSize = new CGSize(UIScreen.MainScreen.Bounds.Size.Width, 50);
              EstimatedItemSize = AutomaticSize;
          }
  
          public override bool ShouldInvalidateLayoutForBoundsChange(CGRect newBounds) {
              return true;
          }
  
          public override UICollectionViewLayoutAttributes LayoutAttributesForItem(NSIndexPath path) {
              return base.LayoutAttributesForItem(path);
          }
  
          public override UICollectionViewLayoutAttributes[] LayoutAttributesForElementsInRect(CGRect rect) {
              return base.LayoutAttributesForElementsInRect(rect);
          }
      }
  </code></pre>
  <pre><code>    public class MessageListDataSource : UICollectionViewDataSource {
  
          private string CellId { get; set; }
  
          #region Computed Properties
          public UICollectionView CollectionView { get; set; }
          public List&lt;int&gt; Numbers { get; set; } = new List&lt;int&gt;();
          #endregion
  
          #region Constructors
          public MessageListDataSource(UICollectionView collectionView, string cellId) {
              // Initialize
              CollectionView = collectionView;
              CellId = cellId;
  
              // Init numbers collection
              for (int n = 0; n &lt; 100; ++n) {
                  Numbers.Add(n);
              }
          }
          #endregion
  
          #region Override Methods
          public override nint NumberOfSections(UICollectionView collectionView) {
              // We only have one section
              return 1;
          }
  
          public override nint GetItemsCount(UICollectionView collectionView, nint section) {
              // Return the number of items
              return Numbers.Count;
          }
  
          public override UICollectionViewCell GetCell(UICollectionView collectionView, NSIndexPath indexPath) {
              // Get a reusable cell and set {~~it's~&gt;its~~} title from the item
              var cell = collectionView.DequeueReusableCell(CellId, indexPath) as MessageListViewCell;
              cell.Text = Numbers[(int)indexPath.Item].ToString();
  
              return cell;
          }
  
          public override bool CanMoveItem(UICollectionView collectionView, NSIndexPath indexPath) {
              // We can always move items
              return true;
          }
  
          public override void MoveItem(UICollectionView collectionView, NSIndexPath sourceIndexPath, NSIndexPath destinationIndexPath) {
              // Reorder our list of items
              var item = Numbers[(int)sourceIndexPath.Item];
              Numbers.RemoveAt((int)sourceIndexPath.Item);
              Numbers.Insert((int)destinationIndexPath.Item, item);
          }
          #endregion
      }
  </code></pre>
  <p>So this should be the base message bubble.</p>
  <pre><code>    public class MessageListViewCell : UICollectionViewCell {
          UIImageView imageView;
  
          public string Text { get; set; }
  
          [Export(&quot;initWithFrame:&quot;)]
          public MessageListViewCell(CGRect 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(1, 1);
              ContentView.AutoresizingMask = UIViewAutoresizing.FlexibleWidth;
  
              imageView = new UIImageView(UIImage.FromBundle(&quot;placeholder.png&quot;));
              imageView.Center = ContentView.Center;
              imageView.Transform = CGAffineTransform.MakeScale(0.7f, 0.7f);
  
              ContentView.AddSubview(imageView);
          }
  
          public UIImage Image {
              set {
                  imageView.Image = value;
              }
          }
  
          [Export(&quot;custom&quot;)]
          public void Custom() {
              // Put all your custom menu behavior code here
              Console.WriteLine(&quot;custom in the cell&quot;);
          }
  
          public override bool CanPerform(Selector action, NSObject withSender) {
              if (action == new Selector(&quot;custom&quot;))
                  return true;
              else
                  return false;
          }
      }
  </code></pre>
  <pre><code>[assembly: ExportRenderer(typeof(MessagesListControl), typeof(MessagesListControlRenderer))]
  namespace Vinder.iOS.UI.Renderers {
  
      public class MessagesListControlRenderer : ViewRenderer&lt;MessagesListControl, UICollectionView&gt; {
  
          static readonly NSString messageListViewCell = new(&quot;MessageListViewCell&quot;);
  
          private UICollectionView collectionView { get; set; }
  
          protected override void OnElementChanged(ElementChangedEventArgs&lt;MessagesListControl&gt; e) {
              base.OnElementChanged(e);
  
              if (e.OldElement != null) {
                  // Unsubscribe to events
              }
  
              if (e.NewElement != null) {
                  if (Control == null) {
                      collectionView = new UICollectionView(new CGRect(0, 0, UIScreen.MainScreen.Bounds.Size.Width, 300), new MessageListLayout());
                      collectionView.RegisterClassForCell(typeof(MessageListViewCell), messageListViewCell);
                      collectionView.BackgroundColor = UIColor.Blue; // blue is easy for seeing the correct bounds
                      collectionView.DataSource = new MessageListDataSource(collectionView, messageListViewCell);
                      SetNativeControl(collectionView);
                  }
  
                  // Subscribe to events
              }
          }
      }
  }
  </code></pre>