xamarin - 如何在 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
元素。
解决方案
很抱歉无法size
从方法中获取视图OnElementChanged
,因为该方法与ViewDidLoad
方法相同。此阶段尚未计算 View 的框架。
我们可以通过get width
and height
fromDraw
方法,这个阶段的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
推荐阅读
- sql - 数据网格替换下一个文件数据而不是在第一个文件之后复制
- php - 我们如何传递参数
- marklogic - MarkLogic - 是否可以配置每分钟运行一次的每周调度程序,直到作业完成
- azure - 有没有办法在 azure cli 中获取当前的 sprint 号?
- python - 如何找到python包SDF的文档?
- excel - 如何在vba中使用自动过滤器
- javascript - 如何在第一个 if 语句为真后停止代码?
- javascript - 对包含字符串的项目使用 JSON 对象上的过滤器
- r - 在 R markdown 中运行任何 R 代码时出错
- python - 使用python解析XML文件时“tag”和“attrib”命令不显示值