xamarin - Xamarin Forms 将不同字体大小的标签垂直对齐到同一基线
问题描述
我在水平方向的堆栈布局中有两个并排的标签。标签有不同的字体大小。无论字体大小如何,我都想让每个标签文本的基线(底部边缘)相同。但是,xamarin 表单的默认行为不是这样做的。以下代码
<StackLayout Orientation="Horizontal" >
<Label FontSize="12" Text="A Noble Spirit"></Label>
<Label FontSize="18" Text="Embiggens The Smallest Man"></Label>
</StackLayout>
在 android 上运行以下视图的结果。
我尝试了许多不同的组合来设置垂直文本对齐和标签上的垂直选项属性。我能想到的最好的(以及我认为应该起作用的)是添加垂直选项=结束它们。这稍微改善了一些情况,但仍然存在不匹配,因此较大标签的文本(embiggens)开始高于较小标签 - 如下所示:
<StackLayout Orientation="Horizontal" >
<Label VerticalOptions="End" FontSize="12" Text="A Noble Spirit"></Label>
<Label VerticalOptions="End" FontSize="18" Text="Embiggens The Smallest Man"></Label>
</StackLayout>
如您所见,有些改进,但仍未对齐。这让我有点上墙了。我开始认为这可能是 Xamarin Forms for android 中的一个错误。(稍后当我可以在 iOS 上运行一个示例以查看它是否特定于 android 时,我将添加到这个问题。)。
我可以通过将顶部边距添加到等于字体大小差异的较小标签来破解它,这很严重,我不想在我的系统中引入技术债务和维护。但这里是为了展示它。希望不必求助于这个...
<StackLayout Orientation="Horizontal" >
<Label FontSize="12" Margin="0,6,0,0" Text="A Noble Spirit"></Label>
<Label FontSize="18" Text="Embiggens The Smallest Man"></Label>
</StackLayout>
解决方案
原因:如果你设置了两个标签的背景颜色,你可以看到,因为标签有一个默认的“填充”。该值取决于它的高度。
解决方案:
您可以将两个不同的字符串放在同一个标签中。它有一个名为FormattedText的属性,它允许您为 Label 设置格式化文本。
<StackLayout Orientation="Horizontal" VerticalOptions="CenterAndExpand" HorizontalOptions="CenterAndExpand">
<Label FormattedText="{Binding FormattedTextContent}" x:Name="label" ></Label>
<Label FormattedText="{Binding FormattedTextContent}" x:Name="label2" ></Label>
</StackLayout>
在后面的代码中
FormattedTextContent = new FormattedString();
var fs = new FormattedString();
fs.Spans.Add(new Span { Text = "A Noble Spirit " , FontSize = 12, TextColor = Color.Black });
fs.Spans.Add(new Span { Text = " ", FontSize = 18 });
label.FormattedText = fs;
var fs1 = new FormattedString();
fs.Spans.Add(new Span { Text = " ", FontSize = 12 });
fs.Spans.Add(new Span { Text = "Embiggens The Smallest Man", TextColor = Color.Black, FontSize = 18 });
label2.FormattedText = fs1;
当然你可以使用 MVVM 因为它是一个可绑定的属性。
推荐阅读
- c++ - 使用带复数的 sstream
- nginx - 将 http 的端口更改为 https -- Nginx
- javascript - JS async / await with fetch 不像 PHP 包含 JSON 文件那样工作
- django - 在 Django 中更改主键导致约束不存在错误
- c# - 在我的后端服务中实例化 DBContext
- mysql - 如何在我的 Ubuntu 台式电脑中完全删除和重新安装 MySQL
- html - 当单独的字符串变长时,为什么文本会改变大小?
- assembly - x86_64 程序集中写入节 .data 的分段错误:
- python - 矢量化物理模拟?
- html - 头等舱孩子的风格不变