Search code examples
objective-cnstableview

NSTableView notification when column resizing has finished?


With an NSTableview I can subscribe to the NSTableViewColumnDidResizeNotification to get events of a column being resized:

[[NSNotificationCenter defaultCenter] addObserver: self
                                         selector: @selector(tableColumnsResized)
                                             name: NSTableViewColumnDidResizeNotification
                                           object: dataTableView];

However, I'm looking to only get a notification once the resizing has finished (so that I can save some details). If I run the code every notification, then the column resizing stutters a bit. This is why I would like to only be notified when the resizing has finished.

Any suggestions how how I could do this?


Solution

  • You should set a short timer whenever you receive the resize notification, cancelling any previous timer. You can then perform your final action in the timer fired method:

    .h:

    @interface MyClass : NSView
    {
        NSTimer *_columnResizeTimer;
    }
    
    @end
    

    .m:

    // Private Methods
    @implementation MyClass ()
    
    - (void)_columnResized:(NSTimer *)timer;
    
    @end
    
    @implementation MyClass
    
    - (void)dealloc
    {
        [_columnResizeTimer invalidate];
        _columnResizeTimer = nil;
    
        // If using MRR:
        [super dealloc];
    }
    
    - (void)tableViewColumnDidResize:(NSNotification *)notification
    {
        [_columnResizeTimer invalidate];
        _columnResizeTimer = [NSTimer scheduledTimerWithTimeInterval:0.5
                                                              target:self
                                                            selector:@selector(_columnResized:)
                                                            userInfo:nil
                                                             repeats:NO];
    }
    
    - (void)_columnResized:(NSTimer *)timer
    {
        [_columnResizeTimer invalidate];
        _columnResizeTimer = nil;
    
        // Do stuff on column resize
    }
    
    @end
    

    (This code is untested and possibly buggy).