【发布时间】:2020-02-12 12:50:27
【问题描述】:
在 Xamarin Forms 中,如果我创建了一个简单的视图,例如 BoxView,然后我使用正确的 AbsoluteLayout.SetLayoutBounds 和 AbsoluteLayout.SetLayoutFlags 放入 AbsoluteLayout,然后如果我尝试使用 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"
}
}
【问题讨论】:
-
您无法获取 x, y,因为该元素尚未在屏幕上绘制。如果您可以像 Task.Delay (2000) 那样设置延迟,您将看到 x、y。但这不是解决方案。
-
@sermet 它仍然不起作用,不断返回 0 和 -1 值,这很奇怪,因为在 iOS 中即使不使用任何延迟也可以工作。
-
尝试通过单击按钮获取坐标。
-
@Nikhileshwar 这样做是可行的,但在我的项目中,当应用程序加载时我需要它们
-
这可能是页面如何在每个平台上呈现自己的情况。您可能必须这样做:forums.xamarin.com/discussion/22561/page-loaded-event
标签: c# xamarin xamarin.forms view coordinates