【问题标题】:How to get UIView size in a Xamarin Forms custom renderer如何在 Xamarin Forms 自定义渲染器中获取 UIView 大小
【发布时间】:2020-06-16 11:23:01
【问题描述】:

我在 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】:

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

    我们可以从Draw方法中得到width和height,这个stage 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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-07-29
      • 2021-12-03
      • 2016-09-03
      • 2018-07-23
      • 1970-01-01
      • 2018-04-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多