Search code examples
cocoaxamarin.mac

How to detect resize in NSView in Xamarin.Mac?


What is the correct way to detect when a NSView is resized ?. I do not see any resize event available on the view or any delegate for the view.

I have added this hack, where I use the drawRect to detect the change in size, but I'm sure there must be a more correct way to do this.

    CGRect m_resizeRect = CGRect.Empty;
    public override void DrawRect(CGRect dirtyRect)
    {
        base.DrawRect(dirtyRect);
        if (this.InLiveResize) {
            if (m_resizeRect.Size != this.Bounds.Size) {
                m_resizeRect = this.Bounds;
                this.OnResize();
            }
        }
    }
    public override void ViewWillStartLiveResize()
    {
        m_resizeRect = this.Bounds;
        base.ViewWillStartLiveResize();
    }
    public override void ViewDidEndLiveResize()
    {
        m_resizeRect = CGRect.Empty;
        base.ViewDidEndLiveResize();
    }
    protected void OnResize() {
        Console.WriteLine("OnResize " + this.Bounds.ToString() );
    }

Solution

  • You can subscribe to the resize notifications.

    Add observer to default notification center:

    NSObject NSWindowDidResizeNotificationObject;
    public override void ViewDidLoad ()
    {
        base.ViewDidLoad ();
        NSWindowDidResizeNotificationObject = NSNotificationCenter.DefaultCenter.AddObserver (new NSString ("NSWindowDidResizeNotification"), ResizeObserver, null);
    }
    

    NSNotification Action:

    public void ResizeObserver (NSNotification notify)
    {
        var r = this.View.Frame;
        Console.WriteLine ("{0}:{1}:{1}", notify.Name, r.Height, r.Width);
    }
    

    Remove observer (and release memory):

    NSNotificationCenter.DefaultCenter.RemoveObserver (NSWindowDidResizeNotificationObject);
    

    Sample Output:

    NSWindowDidResizeNotification:740:740
    NSWindowDidResizeNotification:715:715
    NSWindowDidResizeNotification:681:681
    NSWindowDidResizeNotification:642:642