NET MAUI iOS端CollectionView选中时灰色背景如何设为透明?
解决iOS端CollectionView选中时显示灰色矩形的问题
问题根源是iOS平台下CollectionView的单元格默认带有选中状态的灰色高亮背景,Android端无此默认样式,可通过以下两种方式解决:
方法1:直接设置CollectionView选中背景色
在CollectionView标签中添加SelectedBackgroundColor="Transparent"属性,直接覆盖iOS默认选中背景:
<CollectionView SelectionMode="Single" HeightRequest="50" WidthRequest="250" ItemsLayout="HorizontalList" BackgroundColor="White" SelectedBackgroundColor="Transparent"> <!-- 添加该行 --> <CollectionView.ItemTemplate> <DataTemplate> <Border StrokeThickness="0" WidthRequest="50" HeightRequest="50" StrokeShape="RoundRectangle 25"> <Border StrokeThickness="0" BackgroundColor="Transparent"> <Label Text="{Binding}" HorizontalOptions="Center" VerticalOptions="Center"/> </Border> <VisualStateManager.VisualStateGroups> <VisualStateGroup Name="CommonStates"> <VisualState Name="Normal"/> <VisualState Name="Selected"> <VisualState.Setters> <Setter Property="BackgroundColor" Value="yellow"/> </VisualState.Setters> </VisualState> </VisualStateGroup> </VisualStateManager.VisualStateGroups> </Border> </DataTemplate> </CollectionView.ItemTemplate> <CollectionView.ItemsSource> <x:Array Type="{x:Type x:String}"> <x:String>1</x:String> <x:String>2</x:String> <x:String>3</x:String> <x:String>4</x:String> <x:String>5</x:String> </x:Array> </CollectionView.ItemsSource> </CollectionView>
方法2:自定义iOS平台Handler(适用于方法1不生效的场景)
若方法1无效,可通过自定义Handler彻底禁用默认选中高亮:
- 在iOS项目中创建自定义Handler类:
using Microsoft.Maui.Handlers; using UIKit; namespace 你的应用命名空间.iOS.Handlers; public class CustomCollectionViewHandler : CollectionViewHandler { protected override void ConnectHandler(UICollectionView platformView) { base.ConnectHandler(platformView); platformView.Delegate = new CustomCollectionViewDelegate(); } } public class CustomCollectionViewDelegate : UICollectionViewDelegate { public override void DidSelectItem(UICollectionView collectionView, Foundation.NSIndexPath indexPath) { var cell = collectionView.CellForItem(indexPath); cell.SelectedBackgroundView = new UIView { BackgroundColor = UIColor.Clear }; } }
- 在MauiProgram.cs中注册该Handler:
using 你的应用命名空间.iOS.Handlers; builder.ConfigureMauiHandlers(handlers => { #if IOS handlers.AddHandler<Microsoft.Maui.Controls.CollectionView, CustomCollectionViewHandler>(); #endif });
两种方式均可移除iOS端选中时的灰色背景,保持与Android端一致的UI效果。
内容的提问来源于stack exchange,提问作者pome
相关产品推荐
相关产品推荐

