如何在 Xamarin Forms 自定义渲染器中获取 UIView 大小
How to get UIView size in a Xamarin Forms custom renderer
我在 Xamarin Forms 中创建了一个自定义视图渲染器,想知道视图的大小,以便我可以添加具有绝对定位的子视图。
protected override void OnElementChanged(ElementChangedEventArgs<MyView> e)
{
base.OnElementChanged(e);
if (e.NewElement != null)
{
if (Control == null)
{
var uiView = new UIView
{
BackgroundColor = UIColor.SystemPinkColor
};
SetNativeControl(uiView);
// How to get uiView width and height in absolute numbers?
}
}
}
当我检查 uiView.Frame
时,宽度和高度为 0。
在 PCL 中,MyView
显示为 Grid
元素的子元素。
很抱歉无法从 OnElementChanged
方法获取视图的 size
,因为此方法与 ViewDidLoad
方法相同。这个阶段还没有计算View的frame。
我们可以通过Draw
方法得到width
和height
,这个阶段viewcontroller将开始根据frame的大小在屏幕上绘制view。因此我们现在绝对可以得到尺寸了。
UIView uIView;
public override void Draw(CGRect rect)
{
base.Draw(rect);
Console.WriteLine("------------x" + uIView.Frame.Size.Width);
Console.WriteLine("------------x" + Control.Frame.Size.Width);
Console.WriteLine("------------x" + Control.Bounds.Size.Width);
}
或者其他生命周期在OnElementChanged
之后的方法。比如LayoutSubviews
方法:
UIView uIView;
public override void LayoutSubviews()
{
base.LayoutSubviews();
Console.WriteLine("------------" + uIView.Frame.Size.Width);
Console.WriteLine("------------" + Control.Frame.Size.Width);
Console.WriteLine("------------" + Control.Bounds.Size.Width);
}
输出:
2020-06-16 10:59:11.327982+0800 AppFormsTest.iOS[30355:821323] ------------375
2020-06-16 10:59:11.328271+0800 AppFormsTest.iOS[30355:821323] ------------375
2020-06-16 10:59:11.328497+0800 AppFormsTest.iOS[30355:821323] ------------375
我在 Xamarin Forms 中创建了一个自定义视图渲染器,想知道视图的大小,以便我可以添加具有绝对定位的子视图。
protected override void OnElementChanged(ElementChangedEventArgs<MyView> e)
{
base.OnElementChanged(e);
if (e.NewElement != null)
{
if (Control == null)
{
var uiView = new UIView
{
BackgroundColor = UIColor.SystemPinkColor
};
SetNativeControl(uiView);
// How to get uiView width and height in absolute numbers?
}
}
}
当我检查 uiView.Frame
时,宽度和高度为 0。
在 PCL 中,MyView
显示为 Grid
元素的子元素。
很抱歉无法从 OnElementChanged
方法获取视图的 size
,因为此方法与 ViewDidLoad
方法相同。这个阶段还没有计算View的frame。
我们可以通过Draw
方法得到width
和height
,这个阶段viewcontroller将开始根据frame的大小在屏幕上绘制view。因此我们现在绝对可以得到尺寸了。
UIView uIView;
public override void Draw(CGRect rect)
{
base.Draw(rect);
Console.WriteLine("------------x" + uIView.Frame.Size.Width);
Console.WriteLine("------------x" + Control.Frame.Size.Width);
Console.WriteLine("------------x" + Control.Bounds.Size.Width);
}
或者其他生命周期在OnElementChanged
之后的方法。比如LayoutSubviews
方法:
UIView uIView;
public override void LayoutSubviews()
{
base.LayoutSubviews();
Console.WriteLine("------------" + uIView.Frame.Size.Width);
Console.WriteLine("------------" + Control.Frame.Size.Width);
Console.WriteLine("------------" + Control.Bounds.Size.Width);
}
输出:
2020-06-16 10:59:11.327982+0800 AppFormsTest.iOS[30355:821323] ------------375
2020-06-16 10:59:11.328271+0800 AppFormsTest.iOS[30355:821323] ------------375
2020-06-16 10:59:11.328497+0800 AppFormsTest.iOS[30355:821323] ------------375