在Xamarin Forms中,如果我创建一个简单的视图,例如BoxView
,并使用适当的AbsoluteLayout
和AbsoluteLayout.SetLayoutBounds
将其放置在AbsoluteLayout.SetLayoutFlags
中,那么如果我尝试在其中使用box.X; box.Y, box.Width, box.Height
检索框坐标在Android上,它们的结果为null,0、0,-1,-1。在iOS中,它们可以正确返回。
代码示例
public partial class MainPage : ContentPage
{
BoxView box;
public MainPage()
{
InitializeComponent();
}
protected override void OnAppearing()
{
base.OnAppearing();
box = new BoxView
{
BackgroundColor = Color.Red,
};
AbsoluteLayout.SetLayoutBounds(box, new Rectangle(0.6, 0.6, 0.25, 0.25));
AbsoluteLayout.SetLayoutFlags(box, AbsoluteLayoutFlags.All);
absolutelayout.Children.Add(box);
Console.WriteLine($"Box coordinates: {box.X} {box.Y} {box.Width} {box.Height}");
//IN ANDROID (galaxy s9 emulator): "Box coordinates: 0 0 -1 -1"
//IN IOS (iPhone 11 emulator): "Box coordinates: 186 403 104 224"
}
}
您可以尝试覆盖OnSizeAllocated
方法: