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

我想将Xamarin.Forms中View的高度设置为其内容的大小.例如,我希望Label只与文本一样高.

Android中,我可以执行layout_height =“wrap_content”之类的操作. Xamarin.Forms中有类似的东西吗?我可以使用HeightRequest,如果是这样,怎么样?

最佳答案 当你提到View而不是像Label这样的特定内容时,这是一个非常广泛的问题,因此在不同的View场景中需要考虑一些事项: –

您可以使用View对象的Horizo​​ntalOptions和VerticalOptions属性来帮助解决这个问题,即LayoutOptions.FillAndExpand或LayoutOptions.CenterAndExpand等.

是 – 您可以在视图上指定HeightRequest和WidthRequest,以指示您对通过布局为视图保留的区域宽度和高度的首选项,但这不能保证,这取决于所使用的其他布局控件/视图.

如果我们专门讨论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: –

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

请记住,有时仅在您有兴趣控制的View上设置Horizo​​ntalOptions或VerticalOptions以获得所需效果是不够的.

点赞