如何在Xamarin Forms自定义渲染器中获取UIView大小

问题描述 投票:0回答:1

[我在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元素的子代。

xamarin xamarin.forms uiview xamarin.ios
1个回答
0
投票

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

我们可以从width方法中获得heightDraw,该阶段视图控制器将根据帧的大小开始在屏幕上绘制视图。因此现在我们绝对可以得到大小。

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
© www.soinside.com 2019 - 2024. All rights reserved.