[我在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
元素的子代。
很抱歉无法从size
方法获取View的OnElementChanged
,因为该方法与ViewDidLoad
方法相同。在此阶段尚未计算View的框架。
我们可以从width
方法中获得height
和Draw
,该阶段视图控制器将根据帧的大小开始在屏幕上绘制视图。因此现在我们绝对可以得到大小。
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