如何将视图(fe Label)的高度/宽度设置为其内容的大小?

kao*_*ick 5 layout android view xamarin.forms

我想一个高度设定ViewXamarin.Forms完全相同其内容的大小。例如,我希望 a Labelonly 与其文本一样高。

Android 中,我可以执行类似layout_height="wrap_content". 有没有类似的东西Xamarin.Forms?我可以用HeightRequest这个吗?如果可以,怎么用?

Pet*_*ete 2

当您提到View时,这是一个非常广泛的问题,而不是像Label这样的具体问题,因此在不同的View场景中需要考虑一些事情:-

您可以使用View对象的Horizo​​ntalOptionsVerticalOptions属性来帮助解决此问题,即LayoutOptions.FillAndExpandLayoutOptions.CenterAndExpand等。

是的 - 您可以在视图上指定HeightRequestWidthRequest来指示您对通过布局为视图保留的区域宽度高度的偏好,尽管这不能保证,具体取决于使用的其他布局控件/视图。

如果我们专门讨论标签控件,则这不会扩展所使用的特定标签字体大小的文本大小以适合您指定的父视图。要实现此目的,您必须适当设置Scale属性,以将标签缩放到其所使用的容器。

更新 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;
Run Code Online (Sandbox Code Playgroud)

更新 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;
Run Code Online (Sandbox Code Playgroud)

更新 3:-

这是一个不使用父级设置 Horizo​​ntalOptions/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;
Run Code Online (Sandbox Code Playgroud)

请记住,有时仅在您有兴趣控制的视图上设置Horizo​​ntalOptionsVerticalOptions来获得所需的效果是不够的。