iosmauicollectionview

CollectionView not centered on iOS in MAUI


I want to create a horizontally oriented collection of items centered on the screen. I'm using CollectionView to do so. Using the code below, my CollectionView is centered on Android but is left-justified on iOS. I've tried messing with all the HorizontalOptions for the VerticalStackLayout and CollectionView. I've tried playing around with WidthRequest for both the VerticalStackLayout and CollectionView as well. This definitely seems like a bug, but I'd love to know if any of you have found a workaround or have ideas for one.

In the code below, CollectionViewElements is a simple 3-element List of strings " 1 ", " 2 ", " 3 ".

 <VerticalStackLayout
        Margin="10,30,10,0"
        HorizontalOptions="Center">

        <Label Text="Sample Label - Centered" HorizontalTextAlignment="Center"/>

        <CollectionView ItemsSource="{Binding CollectionViewElements}" HorizontalOptions="Center" SelectionMode="Single"
                        SelectedItem="{Binding Selected}" HeightRequest="20">

            <CollectionView.ItemsLayout>
                <LinearItemsLayout Orientation="Horizontal"/>
            </CollectionView.ItemsLayout>
         </CollectionView>

        <HorizontalStackLayout Margin="0,20,0,0">
            <Label Text="This is the selected item: "/>
            <Label Text="{Binding Selected}"/>
        </HorizontalStackLayout>

    </VerticalStackLayout>

Here is what it looks like on an Android emulator:

enter image description here

Here is is the iPhone emulator:

enter image description here

On Android, it seems that everything in the VerticalStackLayout is Centered. On iOS that is not the case. Also, note that on iOS, the CollectionView starts on the far left edge of the screen even though the left Margin of the VerticalStackLayout that contains it is set to "10". CollectionView seems to ignore it's parent's properties.


Solution

  • That may due to you haven't set a WidthRequest for CollectionView. Otherwise, it doesn't know the width of the CollectionView. Try to set the WidthRequest:

    <CollectionView ItemsSource="{Binding CollectionViewElements}" 
     WidthRequest="50" HeightRequest="20" 
     ...>
    

    Hope it works.