我想在 Xamarin.Forms
中将 View
的高度精确设置为其内容的大小。例如,我希望 Label
只与其文本一样高。
在 Android 中,我可以执行类似 layout_height="wrap_content"
的操作。 Xamarin.Forms
中是否有类似的东西?我可以为此使用 HeightRequest
吗?如果可以,如何使用?
最佳答案
当你提到View时,这是一个非常宽泛的问题,而不是像Label这样的具体问题,所以在不同的View中需要考虑一些事情强>场景:-
您可以使用 View 对象的 HorizontalOptions 和 VerticalOptions 属性来帮助解决这个问题,即 LayoutOptions.FillAndExpand 或 LayoutOptions.CenterAndExpand 等
是的 - 您可以在 View 上指定 HeightRequest 和 WidthRequest 以表明您对区域宽度的偏好和 height 通过 layout 为 view 保留,尽管这不能保证,取决于使用的其他布局控件/ View 。
如果我们专门针对 Label 控件进行对话,这将不会扩展使用的特定 Label 字体大小的文本大小,以适应父级 查看您指定的。为此,您必须适本地设置 Scale 属性,以将 Label 缩放到使用它的容器。
更新 1:-
使用以下示例代码,高度是否已自动更改以适合显示的标签高度文本?
StackLayout cobjStackLayout = new StackLayout()
{
Orientation = StackOrientation.Vertical
};
Label objLabel1 = new Label();
objLabel1.BackgroundColor = Color.Red;
objLabel1.Text = "This is a label";
cobjStackLayout.Children.Add(objLabel1);
Label objLabel2 = new Label();
objLabel2.BackgroundColor = Color.Green;
objLabel2.Text = "This is another label with different font size";
objLabel2.Font = Font.OfSize("Arial", 48);
cobjStackLayout.Children.Add(objLabel2);
this.Content = cobjStackLayout;
更新 2:- 是的 - 在 ContentPage 的末尾有一个意外的垂直填充,当您只使用 一个 Label 时会发生这种情况。
如果您尝试以下操作,您应该只使用1 个标签,在文本周围体验您所追求的:-
cobjStackLayout = new StackLayout()
{
Orientation = StackOrientation.Horizontal,
VerticalOptions = LayoutOptions.Start
};
Label objLabel1 = new Label();
objLabel1.BackgroundColor = Color.Red;
objLabel1.Text = "This is a label";
cobjStackLayout.Children.Add(objLabel1);
this.Content = cobjStackLayout;
更新 3:-
这是一个不使用父级来设置 HorizontalOptions/VerticalOptions 的版本,所以当我说在层次结构的不同部分指定的 LayoutOptions 影响输出时,事情可能会更清楚一些:-
cobjStackLayout = new StackLayout()
{
Orientation = StackOrientation.Horizontal,
};
Label objLabel1 = new Label();
objLabel1.BackgroundColor = Color.Red;
objLabel1.Text = "This is a label";
objLabel1.HorizontalOptions = LayoutOptions.Start;
objLabel1.VerticalOptions = LayoutOptions.Start;
cobjStackLayout.Children.Add(objLabel1);
this.Content = cobjStackLayout;
请记住,有时仅在您有兴趣控制的View 上设置HorizontalOptions 或VerticalOptions 以获得您想要的效果是不够的.
关于android - 如何将 View (例如标签)的高度/宽度设置为其内容的大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25530627/