首页 > 解决方案 > 如何在 Xamarin Forms 自定义渲染器中获取 UIView 大小

问题描述

我在 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元素。

标签: xamarinxamarin.formsuiviewxamarin.ios

解决方案


很抱歉无法size从方法中获取视图OnElementChanged,因为该方法与ViewDidLoad方法相同。此阶段尚未计算 View 的框架。

我们可以通过get widthand heightfromDraw方法,这个阶段的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

推荐阅读