Xamarin表单 - IOS:如何检测UIView大小已更改

时间:2016-09-13 03:54:15

标签: ios xamarin xamarin.ios xamarin.forms

我使用ContentView创建了一个Xamarin表单,并为Android创建了一个渲染器。现在我必须为IOS创建一个渲染器。

在android渲染器中,我可以覆盖onSizeChanged并将这些宽度/高度值传递给自定义xamarin-form视图。

protected override void OnSizeChanged(int w, int h, int oldw, int oldh) { 
        base.OnSizeChanged(w,h, oldw, old);

        Element.SizChanged(w,h);

}

IOS中的UIView是否有类似的覆盖方法?我试过覆盖Frame属性并在Element.SizeChanged(w,h)中调用,但我会得到TargetInvocationException。

P.S。 SizeChanged方法是我的自定义虚方法而不是android方法。

1 个答案:

答案 0 :(得分:1)

覆盖LayoutSubviews通常用于跟踪调整大小事件,因为UIView也对其所有子视图负责。

我倾向于覆盖BoundsFrame,具体取决于我正在做什么以及此视图包含的内容......根据父级视图LayoutSubviews可以被称为很多...

假设UIView子类如:

public class UIViewResizing : UIView
{
    public UIViewResizing() { }
    public UIViewResizing(CGRect frame) : base(frame) { }
    public UIViewResizing(NSCoder coder) : base(coder) { }

    public override CGRect Bounds
    {
        get
        {
            return base.Bounds;
        }
        set
        {
            if (value != base.Bounds)
            {
                Console.WriteLine($"Bounds changing: {this}");
            }
            base.Bounds = value;
        }
    }

    public override CGRect Frame
    {
        get
        {
            return base.Frame;
        }
        set
        {
            if (value != base.Frame)
            {
                Console.WriteLine($"Frame changing: {this}.");
            }
            base.Frame = value;
        }
    }

    public override void LayoutSubviews()
    {
        Console.WriteLine($"LayoutSubViews requested: {this}");
        base.LayoutSubviews();
    }
}

用以下方式行使:

var view = new UIViewResizing(new CGRect(100, 100, 100, 100));
view.BackgroundColor = UIColor.Red;
Add(view);
await Task.Delay(2500);
view.Frame = new CGRect(100, 100, 200, 200);
await Task.Delay(2500);
view.Bounds = new CGRect(20, 20, 100, 200);

结果:

Frame changing: <uiviewresize_UIViewResizing: 0x79a6cc00; frame = (-50 -50; 100 100); layer = <CALayer: 0x78628230>>.
LayoutSubViews requested: <uiviewresize_UIViewResizing: 0x79a6cc00; frame = (100 100; 100 100); layer = <CALayer: 0x78628230>>
Frame changing: <uiviewresize_UIViewResizing: 0x79a6cc00; frame = (100 100; 100 100); layer = <CALayer: 0x78628230>>. 
LayoutSubViews requested: <uiviewresize_UIViewResizing: 0x79a6cc00; frame = (100 100; 200 200); layer = <CALayer: 0x78628230>>
Bounds changing: <uiviewresize_UIViewResizing: 0x79a6cc00; frame = (100 100; 200 200); layer = <CALayer: 0x78628230>>
LayoutSubViews requested: <uiviewresize_UIViewResizing: 0x79a6cc00; frame = (150 100; 100 200); layer = <CALayer: 0x78628230>>

请参阅此SO以获取更多信息:Is there a UIView resize event?