回答
的最佳方式水平居中文本要做到這一點,就要在C#代碼隱藏中創建視圖,因爲在代碼隱藏中,我們可以利用使用Func
來動態調整我們的UI大小,並將UI與其他元素相對齊。
這個堆棧溢出後有關於如何在Xamarin.Forms中心UI元素的詳細信息:
Xamarin.Forms: How to center views using Relative Layout? `Width` and `Height` return -1
示例代碼
using System;
using Xamarin.Forms;
namespace SampleApp
{
public class App : Application
{
public App()
{
var floatingLabel = new Label
{
Text = "This Label Is Centered"
};
var circleImage = new Image
{
Source = "circle"
};
var relativeLayout = new RelativeLayout();
Func<RelativeLayout, double> getfloatingLabelHeight = (p) => floatingLabel.Measure(relativeLayout.Width, relativeLayout.Height).Request.Height;
Func<RelativeLayout, double> getfloatingLabelWidth = (p) => floatingLabel.Measure(relativeLayout.Width, relativeLayout.Height).Request.Width;
Func<RelativeLayout, double> getCircleImageHeight = (p) => circleImage.Measure(relativeLayout.Width, relativeLayout.Height).Request.Height;
Func<RelativeLayout, double> getCircleImageWidth = (p) => circleImage.Measure(relativeLayout.Width, relativeLayout.Height).Request.Width;
relativeLayout.Children.Add(circleImage,
Constraint.RelativeToParent(parent => parent.Width/2 - getCircleImageWidth(parent)/2),
Constraint.RelativeToParent(parent => parent.Height/2 - getCircleImageHeight(parent)/2)
);
relativeLayout.Children.Add(floatingLabel,
Constraint.RelativeToView(circleImage, (parent, view) => view.X + getCircleImageWidth(parent)/2 - getfloatingLabelWidth(parent)/2),
Constraint.RelativeToView(circleImage, (parent, view) => view.Y + getCircleImageHeight(parent)/2 - getfloatingLabelHeight(parent)/2)
);
MainPage = new ContentPage { Content = relativeLayout };
}
}
}
開發你好先生!如果其中一個答案解決了您的問題,請將其標記爲已答覆。這將有助於未來的開發人員提出相同的問題! –