Xamarin iOS 多行按钮ContentLayout图标对齐错位问题
Xamarin Forms iOS端带图标按钮多行显示错位问题
在将Xamarin Forms中带图标的按钮视图适配到iOS平台时,出现了显示异常问题,实际显示效果如下:
已做的基础修复
最初通过自定义渲染器修复了iOS端按钮文本默认仅单行显示的问题,渲染器代码如下:
public class MultiLineButtonRenderer : ButtonRenderer { protected override void OnElementChanged(ElementChangedEventArgs<Button> e) { base.OnElementChanged(e); if (e.NewElement != null) { Control.TitleLabel.LineBreakMode = UIKit.UILineBreakMode.WordWrap; Control.TitleLabel.TextAlignment = UIKit.UITextAlignment.Center; //if (Element.ImageSource != null && Element.ContentLayout.Position == Button.ButtonContentLayout.ImagePosition.Top) //{ //} // Control.ImageEdgeInsets = new UIKit.UIEdgeInsets(0, 50, 0, 50); } } }
涉及的页面XAML代码
出现问题的按钮XAML定义如下:
<StackLayout Orientation="Horizontal" Margin="0,40,0,0"> <Button Text="Disponibilités de l'élève" BackgroundColor="{StaticResource Secondary}" TextColor="{StaticResource Text}" FontAttributes="Bold" CornerRadius="10" ContentLayout="Top,20" WidthRequest="{Binding ButtonWidth}" HorizontalOptions="CenterAndExpand" Command="{Binding OpenAvailabilityModal}"> <Button.ImageSource> <FontImageSource FontFamily="FASolid" Color="{StaticResource Text}" Glyph="{x:Static icons:FontAwesomeIcons.CalendarDays}"/> </Button.ImageSource> </Button> <Button FontAttributes="Bold" CornerRadius="10" ContentLayout="Top,20" WidthRequest="{Binding ButtonWidth}" IsEnabled="{Binding OptionNotTaken}" HorizontalOptions="CenterAndExpand" Command="{Binding SubmitOptionCommand}"> <VisualStateManager.VisualStateGroups> <VisualStateGroup x:Name="CommonStates"> <VisualState x:Name="Normal"> <VisualState.Setters> <Setter Property="BackgroundColor" Value="{StaticResource Secondary}"/> <Setter Property="TextColor" Value="{StaticResource Text}"/> <Setter Property="Text" Value="Poser une option"/> <Setter Property="ImageSource"> <Setter.Value> <FontImageSource FontFamily="FARegular" Color="{StaticResource Text}" Glyph="{x:Static icons:FontAwesomeIcons.CalendarPlus}"/> </Setter.Value> </Setter> </VisualState.Setters> </VisualState> <VisualState x:Name="Disabled"> <VisualState.Setters> <Setter Property="BackgroundColor" Value="LightGreen"/> <Setter Property="TextColor" Value="Green"/> <Setter Property="Text" Value="Option posée"/> <Setter Property="ImageSource"> <Setter.Value> <FontImageSource FontFamily="FARegular" Color="Green" Glyph="{x:Static icons:FontAwesomeIcons.CalendarCheck}"/> </Setter.Value> </Setter> </VisualState.Setters> </VisualState> </VisualStateGroup> </VisualStateManager.VisualStateGroups> </Button> </StackLayout>
具体异常表现
ContentLayout的基础布局逻辑正常,但当按钮文本过长换行后,文本会溢出父容器- 图标始终以渲染器生效前的单行文本位置为基准保持居中,渲染器将文本调整为多行并重新在按钮内部居中后,图标位置不会同步调整,导致图标和文本整体错位
- 目前已知可通过手动设置按钮控件的
ImageEdgeInsets属性修正图标位置,但暂未找到可行的计算方式,实现图标相对于按钮本身居中对齐。
内容的提问来源于stack exchange,提问作者Guillaume D
相关产品推荐
相关产品推荐

