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

时间:2014-08-27 15:03:10

标签: android layout xamarin.forms view

我想将ViewXamarin.Forms的高度精确设置为其内容的大小。例如,我希望Label仅与文本一样高。

Android 中,我可以执行layout_height="wrap_content"之类的操作。 Xamarin.Forms中有类似的内容吗?我可以使用HeightRequest这样做,如果是,怎么做?

1 个答案:

答案 0 :(得分:2)

当您提及查看而不是像标签这样的具体内容时,这是一个非常广泛的问题,因此在不同的视图中需要考虑一些事项场景: -

您可以使用查看对象的 Horizo​​ntalOptions VerticalOptions 属性来帮助解决此问题,即 LayoutOptions.FillAndExpand LayoutOptions.CenterAndExpand 等。

是 - 您可以在查看上指定 HeightRequest WidthRequest ,以表明您对区域 width 的偏好并且 height 将通过布局保留给视图,但这不能保证,这取决于所使用的其他布局控件/视图。

如果我们专门讨论标签控件,则不会扩展所使用的特定标签字体大小的文字大小,以适合父查看您指定的。要完成此操作,您必须根据需要设置比例属性,以将标签扩展为其使用的容器。

更新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 的末尾会出现意外填充,当您使用一个 标签时会发生这种情况。

如果您尝试以下操作,只需使用 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: -

这是一个不使用父设置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;

请记住,有时只需在您感兴趣的查看上设置 Horizo​​ntalOptions VerticalOptions 即可获得所需的效果

相关问题